4

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

Dawid
  • 644
  • 1
  • 14
  • 30

1 Answers1

3

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

Community
  • 1
  • 1
Arthur Ronald
  • 33,349
  • 20
  • 110
  • 136
  • 1
    Is creating an explicit join entity in between still the only solution with `cascade` nowadays? – kagmole Dec 03 '18 at 13:26