2

Code:

@Entity
class Teacher implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
    @Column(nullable = false)
    @NotNull
    String name;
    @OneToMany(mappedBy = "teacher",cascade = CascadeType.REMOVE)
    List<Course> courses;
}

@Entity
public class Course implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
    @Column(nullable = false)
    @NotNull
    String name;
    @ManyToOne(cascade = CascadeType.REMOVE)
    Teacher teacher;
}

Three questions:

  1. Must I put CascadeType.REMOVE in both entities? I want it to work so that if I delete the teacher the course will be deleted automatically.

  2. In my database my id doesn't work normally. I want it so that the id increments by one each time, but it currently increases by some random number. Why?

  3. I have 2 more @Entity Classes but with @ManyToMany relationship. What must I to do when I want to persist a new object in the database?

Fernando Carvalhosa
  • 1,098
  • 1
  • 15
  • 23
user3521250
  • 115
  • 3
  • 14

1 Answers1

0
  1. Probably a duplicate of one of these:
    JPA: Cascade remove does not delete child
    JPA 2.0 orphanRemoval=true VS on delete Cascade
    https://stackoverflow.com/questions/22237631/jpa-does-not-cascade-delete-operation-from-parent-entity-to-child-entity
    Have you checked those references?

  2. Need more intel

  3. You can persist each of them alone or an instance of Class A with an instance of Classe B attached or vice versa (assuming that you are using the proper CascadeType and @ManyToMany relationship and persistence framework that understands those two)

Community
  • 1
  • 1
Fernando Carvalhosa
  • 1,098
  • 1
  • 15
  • 23
  • many thanks, the delete on cascade work perfectly.the 3 question my question is what i must to do if i want to persist entity if i have @ManyToMany relationship. – user3521250 May 28 '14 at 14:01
  • I'm glad it works. Edited my answer about question number 3. If you need, i can find a real example to help clarifying it – Fernando Carvalhosa May 29 '14 at 04:02