Я пытаюсь реализовать двунаправленное отображение ManyToMany в Hibernate.Но когда я тестирую приложение, сохраняя сторонний объект, не являющийся владельцем, 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 (?)
Спасибо.