I have two tables in my database. The first table auto generates its primary key and I want the second table to get its primary key from the PK of the first table. Is it possible to implement this using hibernate as when I don't include a @GeneratedValue tag on the PK column of the second table it throws an error.
Asked
Active
Viewed 208 times
1
-
Why do they share the primary key? Is it a OneToOne relationship or more something like inheritance? – Simon Martinelli Sep 25 '19 at 06:01
-
It is a one to one relationship – Poppy Sep 25 '19 at 06:15
-
Possible duplicate of [can someone please explain me @MapsId in hibernate?](https://stackoverflow.com/questions/9923643/can-someone-please-explain-me-mapsid-in-hibernate) – XtremeBaumer Sep 25 '19 at 06:18
1 Answers
0
suppose it is your primary table: having these
Table/class 1
@Entity
@Table(name="primetable")
public class PrimeTable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
int id;
...
...
...
Table/class 2
@Entity
@Table(name="secondtable")
public class SecondTable{
@ManyToOne
@JoinColumn(name="prime_id", nullable=false) // this is fk in sec. table
PrimeTable primetable;
...
...
...
When you actually writing into db
public SecondTable simpleSave(SecondTable secondtable) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
// these following two line take care of your primary key
session.saveOrUpdate(secondtable.getPrimeTable());
session.saveOrUpdate(secondtable);
//Commit transaction to save it to db
session.getTransaction().commit();
//Close the session and release database conn
session.close();
System.out.println("primetable added to db ID: " + primetable.getId());
return primetable;
}
Rememeber, during getter/setter don't set your Id yourself, also remember it will create duplicate in child table, and parent table will give you exception message you may handle it before hit commit or saveOrUpdate

shariqayaz
- 63
- 1
- 8