简体   繁体   English

Hibernate没有设置外键

[英]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. 我正在尝试用这个简单的例子来学习Hibernate但是我在使用外键时遇到了麻烦,它在数据库中仍然是“空”。

@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. 但是当Isavethe id_tb2(在表tb1中)没有设置并且它仍然为空。 What I'm missing? 我错过了什么?

The problem you have to set the relation on both sides for a bidirectional relationship. 您需要为双向关系设置双方关系的问题。

So you have to set your relationship for CD and your Track object and persist/merge them afterwards. 因此,您必须为CDTrack对象设置关系,然后保留/合并它们。

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. 有关详细信息,请参阅其他问题

I think your type of the table2 我认为你的表2的类型

private tb2 cd;

should be changed as 应改为

private CD cd;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM