【发布时间】:2019-02-01 20:38:06
【问题描述】:
应用程序正在使用 Hibernate 3,我一直在阅读 JPA 注释与 Hibernate 注释的一些问题。见Cascade common mistakes。
我正在使用旧代码,因此实体完全一团糟。
以前我的实体是:
@OneToMany(mappedBy = "order", targetEntity = Investiment.class, fetch = FetchType.LAZY)
@Cascade({org.hibernate.annotations.CascadeType.ALL,
org.hibernate.annotations.CascadeType.DELETE_ORPHAN,
org.hibernate.annotations.CascadeType.PERSIST,
org.hibernate.annotations.CascadeType.MERGE,
org.hibernate.annotations.CascadeType.REMOVE,
org.hibernate.annotations.CascadeType.REFRESH,
org.hibernate.annotations.CascadeType.SAVE_UPDATE})
private List<Investment> investment;
@ManyToMany(
cascade = {CascadeType.PERSIST},
targetEntity = Discount.class,
fetch = FetchType.EAGER)
@JoinTable(name = "cupons_campanha_pedido")
private List<Discount> discountList;
@Column(name = "nfeAccessKey")
private String nfeAccessKey;
@OneToMany(cascade = {CascadeType.ALL})
@Cascade(value = {org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@JoinColumn(name = "idOrder")
@LazyCollection(LazyCollectionOption.FALSE)
private List<Item> itens;
我有很多对象引用一个未保存的瞬态实例 - 在刷新之前保存瞬态实例:com.company.entity.Investment
对我来说,将 CascadeType.ALL 设置为非常奇怪的设置并再次设置所有可能的枚举。所以我只更改投资注释:
@OneToMany(mappedBy = "order", targetEntity = Investment.class, fetch = FetchType.LAZY)
@Cascade({org.hibernate.annotations.CascadeType.ALL})
private List<Investment> investment;
第一个异常停止。但是我知道我得到了这个(不常见但会发生):
警告 - 2019-01-31 19:25:18.470:SQL 错误:0,SQLState:23503 错误 - 2019-01-31 19:25:18.471:批次条目 0 从订单中删除 id=1096523 被中止:错误:更新或删除表“订单” 违反表上的外键约束“fk10e0b022beb033fc” "orderinvestment" 详细信息:Key (id)=(1096523) 仍被引用 来自表“订单投资”。调用 getNextException 查看其他 批处理中的错误。警告 - 2019-01-31 19:25:18.471:SQL 错误:0, SQLState:23503 错误 - 2019-01-31 19:25:18.472:错误:更新或 删除表“订单”违反外键约束 表“orderinvestment”上的“fk10e0b022beb033fc”详细信息:键 (id)=(1096523) 仍然从表“orderinvestment”中引用。 错误 - 2019-01-31 19:25:18.472:无法同步数据库状态 与会话 org.hibernate.exception.ConstraintViolationException: 无法执行 JDBC 批量更新 org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71) 在 org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
调用时会发生这种情况
getHibernateTemplate().saveOrUpdate(entity);
我知道 Hibernate 是一个 JPA 实现,但是使用 JPA 注释存在一些问题。所以最好只使用 Hibernate 注释。在这种情况下,Investment 设置为 org.hibernate.annotations.CascadeType.ALL。为什么会这样?
【问题讨论】:
标签: java hibernate jpa orm foreign-keys