在Hibernate @ManyToMany双向映射中保留非所有者副对象不会在联接表中保留数据

时间:2018-09-24 16:22:57

标签: java hibernate

我正在尝试在Hibernate中实现ManyToMany双向映射。但是,当我通过持久保存非所有者副对象来测试应用程序时,Hibernate不会在连接表中持久保存数据。

这是我的代码:

College.java:

@Entity
@Table(name="college")
public class College {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="college_id")
    private int id;

    @Column(name="college_name")
    private String name;

    @ManyToMany(mappedBy="colleges",cascade=CascadeType.ALL)
    private Set<Certification> certifications;

    // getters and setters
}

Certification.java:

@Entity
@Table(name="certification")
public class Certification {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="certification_id")
    private int id;

    @Column(name="certification_name")
    private String name;

    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name="certification_college",joinColumns=@JoinColumn(name="certification_id"),inverseJoinColumns=@JoinColumn(name="college_id"))
    private Set<College> colleges;

    // getters and setters
}

MainApplication.java:

public class MainApplication{

    public static void main(String[] args) {

        Certification certification1 = new Certification();
        certification1.setName("Java");

        Certification certification2 = new Certification();
        certification2.setName("C++");

        Set<Certification> certifications = new HashSet<Certification>();
        certifications.add(certification1);
        certifications.add(certification2);

        College college1 = new College();
        college1.setName("ABC");
        college1.setCertifications(certifications);

        College college2 = new College();
        college2.setName("XYZ");
        college2.setCertifications(certifications);

        SessionFactory sessionFactory =  HibernateUtil.getSessionFactory();
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();

        session.save(college1);
        session.save(college2);

        transaction.commit();
        sessionFactory.close(); 
    }
}

以下是SQL输出:

Hibernate: insert into college (college_name) values (?)
Hibernate: insert into certification (certification_name) values (?)
Hibernate: insert into certification (certification_name) values (?)
Hibernate: insert into college (college_name) values (?)

谢谢。

1 个答案:

答案 0 :(得分:0)

您在College.java类中缺少@JoinTable批注。您将保留一个不知道映射关系表的实体。

在“证书”属性的@ManyToMany注释后添加以下代码。

@JoinTable(name="certification_college",joinColumns=@JoinColumn(name="college_id"),inverseJoinColumns=@JoinColumn(name="certification_id"))