Cascade deleting from join table with @ManyToMany annotation

筅森魡賤 提交于 2019-12-07 12:14:53

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/4566614/cascade-deleting-from-join-table-with-manytomany-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!