【问题标题】:JPA one-to-one entity removal in bidirectional relationship双向关系中的 JPA 一对一实体删除
【发布时间】:2013-03-05 09:47:44
【问题描述】:

这是我的学生实体,

@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;
  .....
  ...
  ..
}

这是我的 StudentContact 实体,如下所示,

@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;
   ........
   ......
   ....
   ..
   .
}

我的 StudentTest.java 包含我尝试做的主要方法:

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

上述操作不会删除 StudentContact 实体。 当我检查日志时,它只显示了 StudentContact 和 Student 的 Select 查询,但没有打印 Delete 查询,也没有显示任何异常。

我哪里错了?

【问题讨论】:

    标签: jpa sql-delete one-to-one bidirectional


    【解决方案1】:

    可能存在从 Student 到 StudentContact 的参照完整性约束(外键)。所以你不能删除 StudentContact 因为 student 会指向不存在的实体。

    你必须先去掉这个引用,比如:

    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(); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多