使用@ManyToMany批注从连接表中删除级联

时间:2010-12-30 22:02:49

标签: hibernate annotations jpa-2.0 cascade cascading-deletes

您好我的实体映射问题。我正在使用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中的任何内容。

获得它的最佳方法是什么?

由于 的Dawid

1 个答案:

答案 0 :(得分:3)

您可以将@ManyToMany拆分为@ OneToMany-ManyToOne,并设置如图所示的级联样式here虽然问题使用Hibernate的会话,但您可以使用JPA EntityManager。或者使用新的JPA功能@ElementCollection(仅限JPA 2)来映射您加入的类。请参阅here如何操作。只需用@ElementCollection

替换Hibernate的@CollectionOfElements