使用@ManyToMany注释从连接表中级联删除
您好,我在映射实体时遇到问题。我正在使用 JPA2 和 Hibernate 实现。我得到带有 @ManyToMany 注释的表
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 中的任何内容都无法删除。
获得它的最佳方式是什么?
谢谢 大卫
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
I mapped it with :
@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; ...}
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?
Thanks
Dawid
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将 @ManyToMany 拆分为 @OneToMany-ManyToOne 并设置级联样式,如此处所示使用Hibernate的session,可以使用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