简体   繁体   English

在我的情况下,提交JPA事务的最佳方法是什么?

[英]How is the best way to do commit JPA transaction in my case?

Assume I have 3 Entity Model: 假设我有3个实体模型:

History.class
DetilHistory.class
Logs.class

I have to write my code like this: 我必须这样写我的代码:

//Create History
History h = new History(new Date(), 1, 1, 1);
h.save();

//Create Detil History
DetilHistory dh = new DetilHistory(1, 1, 1, h.id);
dh.save();

//Create Logs
Logs l = new Logs(1,1,1,dh.id);
l.save();

I have to get h.id first for dh.referecendIdOfHistory. 我必须先为dh.referecendIdOfHistory获取h.id。 AND I have to get dh.id first for l.referecendIdOfDetilHistory. 而且我必须先为dh.id获取l.referecendIdOfDetilHistory。

BUT, Sometimes i have to change the variable h or dh below that code like this: 但是,有时我必须在该代码下更改变量h或dh,如下所示:

h.closeDate= new Date();
h.value = 2;
h.save();

I do it for Detil History too. 我也为Detil History做这件事。

Unfortunately JPA can't do it like that. 不幸的是,JPA无法做到这一点。 I know the reason why JPA don't allow that. 我知道JPA不允许这样做的原因。

I have issues about: 我有以下问题:

  • detached entity passed to persist 分离的实体传递给持久化
  • JPA has not been initialized JPA尚未初始化
  • etc 等等

I have solved them with: 我用以下方法解决了它们:

- JPAPluginStartTx(rollback)
- JPA.em().flush(); JPA.em().getTransaction().commit();

Somebody please could tell me how the best way to do it? 有人可以告诉我最好的方法吗?

What do your save() methods do? 您的save()方法有什么作用? Maybe you could try getting an EntityManager instance, opening a transaction with em.getTransaction().begin, then persisting all the entities in order, then committing the transaction. 也许您可以尝试获取EntityManager实例,使用em.getTransaction()。begin打开事务,然后按顺序持久化所有实体,然后提交事务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM