This is my Student entity,

@Entity
@Access(AccessType.FIELD)
@Table(name="TBL_STUDENT")
public class Student  implements  Serializable{
  .....
  .....
  ....
  ..
  .
  @OneToOne(  targetEntity=StudentContact.class,
              fetch=FetchType.LAZY,
              cascade={CascadeType.ALL}
           )
  @JoinColumn(name="CONTACT_ID")
  private StudentContact contact;
  .....
  ...
  ..
}

This is my StudentContact entity as follows,

@Entity
@Table(name="TBL_STD_CONTACT")
public class StudentContact implements Serializable{
   ......
   ....
   ..
   @OneToOne(  mappedBy="contact",
               targetEntity=Student.class,
               cascade={
                         CascadeType.PERSIST,
                         CascadeType.MERGE
                       }
               fetch= FetchType.LAZY)
   private Student student;
   ........
   ......
   ....
   ..
   .
}

My StudentTest.java contains the main method, where I try to do:

tx = em.getTransaction();   
tx.begin();  
StudentContact contact = em.find(StudentContact.class,38);
em.remove(contact);  
tx.commit(); 

The above operation does not delete the StudentContact entity. When I check the log, it just shows the Select query for StudentContact and Student, but it does not print the Delete query, also does not show any exception.

Where am I going wrong?

有帮助吗?

解决方案

There is probably referential integrity constraint (Foreign Key) from Student to StudentContact. So you can't remove StudentContact because student would point to nonexistent Entity.

You have to get rid of this reference first, something like:

tx = em.getTransaction();   
tx.begin();  
StudentContact contact = em.find(StudentContact.class,38);
Student student = contact.getStudent();
student.setContact(null);
contact.setStudent(null);
em.merge(student);
em.remove(em.merge(contact));
tx.commit(); 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top