1

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.

Poppy
  • 11
  • 2

1 Answers1

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