我正在嘗試進行插入,并使用生成的實體更新同一事務中的 N 條記錄。出現錯誤“FK 不存在”,觀察查詢的日志跟蹤以觸發指令的相反順序執行。服務:@Transactionalpublic Entity1 createEntity(Entity1 newEntity){ Entity1 inserted = dao.createEntity(newEntity); Integer numUpdated = dao.updateEntity2(newEntity) return inserted;}Dao:public Entity1 createEntity(Entity1 newEntity){ this.em.persist(newEntity); //now newEntity has PK return newEntity;}public Integer updateEntity2(Entity1 newEntity){ CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<Entity2> uq = cb.createCriteriaUpdate(Entity2.class); Root<Entity2> rootEntity2 = uq.from(Entity2.class); uq.set(rootEntity2 .get(Entity2_.entity1), newEntity); return em.createQuery(uq).executeUpdate(); }實體:@Entitypublic class Entity1 implements Serializable { [...] @OneToMany(mappedBy="entity1",fetch=FetchType.LAZY) private List<Entity2 > entity2s; [...]}@Entitypublic class Entity2 implements Serializable { [...] @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="E1_ID") private Entity1 entity1; [...]}這個想法是不必用刷新來關閉事務,因為我知道寫下事務性的方法應該允許這樣做
1 回答

喵喵時光機
TA貢獻1846條經驗 獲得超7個贊
根據jpa 2.1的api
CriteriaUpdate 接口定義了使用 Criteria API 執行批量更新操作的功能。Criteria API 批量更新操作直接映射到數據庫更新操作,繞過任何樂觀鎖定檢查。如果需要,使用批量更新操作的便攜式應用程序必須手動更新版本列的值,和/或手動驗證版本列的值。?持久性上下文與批量更新的結果不同步。
CriteriaUpdate 對象必須有一個根。
PSD 2.1 火
在某些示例中,他們手動管理事務性,在 catch 子句中使用 em.getTransaction().commit()、em.getTransaction().rollback() 等
添加回答
舉報
0/150
提交
取消