不删除hibernate中的子行

时间:2016-11-29 10:53:05

标签: hibernate fluent-nhibernate hibernate-mapping

我的网络应用程序中有两个实体。一个是UserDetails,另一个是OrderDetails。

@Entity
@Table(name="USER_DETAILS")
public class UserDetails {

@OneToMany(cascade=CascadeType.ALL,orphanRemoval=true)
@JoinTable(name="USER_CART",
            joinColumns=@JoinColumn(name="USER_ID"),
            inverseJoinColumns=@JoinColumn(name="CART_ID")
        )

private Collection<CartList> cartList= new ArrayList<CartList>();

public Collection<CartList> getCartList() {
    return cartList;
}
public void setCartList(Collection<CartList> cartList) {
    this.cartList = cartList;
}

}

我正试图通过以下代码从UserDetails中删除CartList。

List<CartList> cartLists=new ArrayList<>();

    try{

    Query<CartList> query=session.createQuery("from UserDetails where userEmail=?");
    query.setString(0, user);

    cartLists=query.list();

    System.out.print(String.valueOf(cartLists));

    for(CartList temp:cartLists){

        session.delete(temp);

    }

    session.getTransaction().commit();
    }catch (Exception e) {
        return "unsuccessful";
    }

但是下面的代码抛出错误。

   WARN [http-nio-8080-exec-6]     org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions SQL Error: 1451, SQLState: 23000
ERROR [http-nio-8080-exec-6] org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions Cannot delete or update a parent row: a foreign key constraint fails (`ebdb`.`USER_CART`, CONSTRAINT `FKcdargk7kuorrqnumdp06jtqua` FOREIGN KEY (`CART_ID`) REFERENCES `CART_LIST` (`id`))
 INFO [http-nio-8080-exec-6] org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl.release HHH000010: On release of batch it still contained JDBC statements
ERROR [http-nio-8080-exec-6] org.hibernate.internal.ExceptionMapperStandardImpl.mapManagedFlushFailure HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]

请帮助我。我不明白我做错了什么。请帮助我。

1 个答案:

答案 0 :(得分:0)

您正在尝试从父表(OrderDetails)中删除记录与子表(UserDetails)相关联的记录,这意味着父表列在您的子表中用作外键(CART_ID),您必须先从子表中删除数据表对应父表中的记录。 另一个问题是,在创建表时,您必须指定条件是否要删除与父记录关联的所有子记录。 例如:

 CREATE TABLE PADRE{
IDPADRE INT PRIMARY KEY
IDABUELO INT CONSTRAINT FK_IDABUELO FOREIGN KEY IDABUELO REFERENCES ABUELO(IDABUELO) ON DELETE CASCADE
}