使用@ManyToMany 注释从连接表中级联删除 [英] Cascade deleting from join table with @ManyToMany annotation
问题描述
我在映射实体时遇到问题.我正在使用 JPA2 和 Hibernate 实现.我得到了带有@ManyToMany 注释的表格
Hi I got a problem with mapping my entities. I'm using JPA2 and Hibernate implementation. I got tables with @ManyToMany annotation
http://img204.imageshack.us/img204/7558/przykladd.png
我用:
@Entity
@Table("employee")
class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String name;
@ManyToMany
@JoinTable(name = "proj_emp",
joinColumns = @JoinColumn(name = "employee_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"),
uniqueConstraints = @UniqueConstraint(columnNames = {"employee_id", "project_id"}))
private List<Project> projects; ...}
@Entity
@Table("project")
class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String name;
@Column
private Integer budget;
@ManyToMany(mappedBy = "projects")
private List<Employee> employees; ...}
现在,当我从 Employee 中删除记录时,我想从表 proj_emp 中进行级联删除,但无法删除表 Project 中的任何内容.
Now I would like to have a cascade deleting from table proj_emp when I delete records from Employee, but nothing from table Project can be deleted.
获得它的最佳方式是什么?
What is the best way to acquire that?
谢谢大卫
推荐答案
您可以将@ManyToMany 拆分为@OneToMany-ManyToOne 并设置级联样式,如图所示here 虽然问题使用的是Hibernate的会话,但您可以使用JPA EntityManager.或者使用新的 JPA 功能 @ElementCollection(仅限JPA 2) 映射您加入的类.请参阅此处如何操作.只需将 Hibernate 的 @CollectionOfElements 替换为 @ElementCollection
You can split your @ManyToMany into a @OneToMany-ManyToOne and set up a cascading style as shown here Although the question uses Hibernate's session, you can use JPA EntityManager. Or use the new JPA feature @ElementCollection (Only JPA 2) to map your joined class. See here how to. Just replace Hibernate's @CollectionOfElements by @ElementCollection
这篇关于使用@ManyToMany 注释从连接表中级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!