Stefano Pisano
Stefano Pisano

Reputation: 438

Hibernate not setting foreign key

I'm trying to learn Hibernate with this simple example but I'm having so trouble with the foreign key which remains "null" in the database.

@Entity
@Table(name = "tb1")
public class Track {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="id_tb1", unique= true)
    private int id_tb1;
    @Column(name = "title")
    private String title;
    @ManyToOne
    @JoinColumn(name="id_tb2")
    private tb2 cd;

And this is the second class

@Entity
@Table(name = "tb2")
public class CD {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="id_tb2", unique = true)
    private int id_tb2;
    @Column(name="title")
    private String title;
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL,mappedBy = "cd")
    private List<tb1> tracks = new ArrayList<tb1>();

I save like this:

SessionFactory factory = new Configuration().configure("/resources/hibernate.cfg.xml").buildSessionFactory();
                Session session1 = factory.openSession();
                session1.beginTransaction();
                session1.save(tb2);
                session1.getTransaction().commit();

but when Isavethe id_tb2 (in the table tb1) is not set and it remains null. What I'm missing?

Upvotes: 1

Views: 311

Answers (2)

Paul Wasilewski
Paul Wasilewski

Reputation: 10372

The problem you have to set the relation on both sides for a bidirectional relationship.

So you have to set your relationship forCD and your Track object and persist/merge them afterwards.

Without seeing to much of your code you have to do something like.

cd.getTracks().add(track);
track.setCD(cd);
session1.save(track);
session1.save(cd);

See another question for more details.

Upvotes: 2

Tharsan Sivakumar
Tharsan Sivakumar

Reputation: 6531

I think your type of the table2

private tb2 cd;

should be changed as

private CD cd;

Upvotes: 1

Related Questions