Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[eclipselink-users] JPQL does not do cascading delete

I'm using JPA2.0 and EclipseLink 2.3. Same results on Oracle 11g and MySQL 5.1.

Below are at the bottom. An exam paper (ExamPaper) contains many questions(Question); each question has four options (QuestionOption).

I want to delete all ExamPapers and their related questions and options. However I found that JPQL's delete statement does not do cascading deletion, even I've already set cascade=ALL and orphanRemoval=true.

While EntityManager.remove does do cascading deletion.But I don't think it's a good idea to delete one by one.

Am I missing something? How can I delete records with cascade on?


--------------- ExamPaperDao.java ----------------------
  public void clearExamPapers() {
    int count = 0;
    EntityManager em = createEntityManager();
    try {
      EntityTransaction tx = em.getTransaction();
      try {
        Query query = em.createQuery("delete from ExamPaper");
        tx.begin();
        count = query.executeUpdate();
        tx.commit();
      } finally {
        if(tx.isActive()) tx.rollback();
      }
    } finally {
      em.close();
    }
    log.trace("ExamPapers cleared: [count={}]", count);
  }

---------------- Entities ------------------------------
@Entity
public class ExamPaper {
  @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;
  @OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, cascade = {CascadeType.ALL})
  List<Question> questions;

  ... constructors, getters and setters, equals and hashCode excluding id
}

@Entity
public class Question {
 
  @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String serial;
  private String title;
  @OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.ALL)
  @JoinColumn(name = "question_id")
  //@OrderBy()
  private List<QuestionOption> options;

  ... constructors, getters and setters, equals and hashCode excluding id
}

@Entity
public class QuestionOption {
  public enum OptionLabel { A, B, C, D }
 
  @Id @GeneratedValue(strategy =GenerationType.IDENTITY)
  private Long id;
  @Enumerated(EnumType.STRING)
  private OptionLabel label;
  private String text;
  private Boolean checked;

  ... constructors, getters and setters, equals and hashCode excluding id
}

-- ------------
Regards,
Warren Tang

Back to the top