2015-12-04 58 views
1

我还在学习很多的休眠的东西,在休眠表之间有关系处理于是在我的项目之一,我面临着以下问题:不能删除或更新父行,外键约束失败冬眠

有什么问题?

我有一个包类(这是一个实体类)

@Entity 
public class Package { 
@OneToOne(fetch = FetchType.EAGER) 
    User sender; 
    /*rest of class getter setter etc*/ 
} 

我有一个用户类(这又是一个实体)

@Entity 
public class User { 
    @oneToOne 
    Person person; 
/*rest of user class*/ 
} 
@Entity class Person { 
    /*email etc*/ 
} 

什么,我想做?

我试图删除套餐实体,而不删除在包表

我打电话通过packageDAO

@Override 
public void remove(E entity) { 
    try { 
     transaction = currentSession().beginTransaction(); 
     if (transaction == null) { 
      throw new GenericDAOException(TRANS_NULL); 
     } 
     currentSession().delete(entity); 
     transaction.commit(); 

    } catch (final HibernateException he) { 
     if (transaction != null) { 
      // Transaction has to be rolled back when exception is thrown 
      transaction.rollback(); 
     } 
     throw new GenericDAOException(he.getCause().toString()); 
    } 
    currentSession().close(); 
} 

我得到什么错误的套餐实体删除所提及的用户?

exception.GenericDAOException:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:不能删除或更新父行:外键约束失败(mydbuser_table,约束FK_o0l5sy9ohe6iy6fqutl68hc3l外键(person_id)参考文献person_tableperson_id ))

我迄今试图

几个,我试图匹配这些职位,但我没能达到预期的效果,使用​​的解决方案实际上将删除该用户也同时删除这是不是我要找的包,少数职位,我已经提到包括:

@OneToMany errors in MySQL: Cannot delete or update a parent row: a foreign key constraint fails

Cannot delete or update a parent row: a foreign key constraint fails (hibernate xml mapping)

如果有的话这将是巨大你可以通过休眠一些灯,我怎样才能删除一个实体,而不删除另一个实体@OneToOne映射关系

+0

检查类似的问题已经在这里回答: [无法删除或更新父行ConstraintViolationException](http://stackoverflow.com/questions/40641181/cannot-delete-or-update-a-parent-row-constraintviolationexception/40645955#40645955) –

回答

0

你需要做的是首先删除包和用户的关系(设置用户的fk in包null)。你可以通过在Package实体中将sender设置为null并更新它。一旦完成,您可以轻松删除Package实体而不删除User实体。

相关问题