0

I have been developing a web application running on the Glassfish Server. I use JPA with EclipseLink implementation.

These are my two entity classes. I represent the relation between them below. When I start the Glassfish server and delete the lesson entity, Cascade works. It deletes all of the Test entities of it. Then I add lesson entity and test entity related to it. But when I try to delete the Lesson entity, at this time Cascade does not work and throws "foreign key constraint" error. After Server restarting, Cascade again works. ??? What is the difference? Why do Cascade operation only work at the startup?

Thank you.

@Entity
public class Lesson implements Serializable {

    ...

 @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.MERGE, CascadeType.REMOVE }, mappedBy = "lesson" )
private List< Test >        tests;

    ...
}

@Entity
public class Test implements Serializable {

   ...

   @ManyToOne( targetEntity = Lesson.class, fetch = FetchType.LAZY )
   @JoinColumn( name = "lessonNo", insertable = true, updatable = true, nullable = false )
   private Lesson               lesson;

   ...
}
Softengilker
  • 173
  • 1
  • 3
  • 11
  • 1
    Do you manualle persist both entities when you create them? The relation is bidirectional so you need to set/add the other entity on both of them, do you do that? Also do you use JTA or resource_local? – Jaqen H'ghar Nov 15 '14 at 10:49
  • I use JTA, yes I added both entities. I did not insert them manually. – Softengilker Nov 15 '14 at 16:02
  • As Jaqen mentioned, this issue is common when not correctly setting and maintaining both sides of a bidirectional relationship. Show the code you are using, and also try querying before your delete using "Select t from Test t where t.lesson.id=:id", passing in your lesson id, and compare the collection returned to your lesson's tests list. Chances are you have removed one or two from the collection within your code somehow. Calling em.remove(em.refresh(lesson)); should resolve the issue, but you should track down how it is occurring in your code so it can be fixed. – Chris Nov 17 '14 at 13:40

0 Answers0