如果我坚持后分离,为什么找不到实体
我有带有容器管理事务的无状态会话 Bean。我想在数据库中创建(保留)非托管实体后返回它。我就是这样做的:
@Stateless
public class MyBean {
@EJB(name="MyController")
private MyController myController;
public MyEntity create(MyEntity entity) {
//...
myController.create(entity);
myController.preTransfer(entity);
return entity;
}
}
@Stateless
public class MyController {
@PersistenceContext(unitName = "myPU")
private EntityManager em;
public void create(MyEntity entity) {
//...
em.persist(entity);
}
public void preTransfer(MyEntity entity) {
if (em.contains(entity)) {
em.detach(entity);
}
//...
}
}
我调用 MyBean.create,实体成功持久化,并且 MyBean.create 返回非托管实体,没关系。但下次当我尝试通过 id 检索该实体时,却找不到它。如果我评论分离,可以找到实体,但MyBean.create在这种情况下返回托管实体。我哪里错了?
I have Stateless Session Bean with Container-Managed Transactions. I want to return unmanaged entity after create (persist) it in a database. That's how I do it:
@Stateless
public class MyBean {
@EJB(name="MyController")
private MyController myController;
public MyEntity create(MyEntity entity) {
//...
myController.create(entity);
myController.preTransfer(entity);
return entity;
}
}
@Stateless
public class MyController {
@PersistenceContext(unitName = "myPU")
private EntityManager em;
public void create(MyEntity entity) {
//...
em.persist(entity);
}
public void preTransfer(MyEntity entity) {
if (em.contains(entity)) {
em.detach(entity);
}
//...
}
}
I call MyBean.create, entity successfully persisted and MyBean.create return unmanaged entity, that's ok. But next time when I try retrieve this entity by id, it can't be found. If I comment detach, entity can be found, but MyBean.create return managed entity in that case. Where I am wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
EntityManager.detach
状态:所以你要持久化它,然后分离它。但与 persist 相关的操作尚未刷新,因此该实体尚未保存到数据库中。
为什么要拆开它?一旦交易结束,它将自动分离。
The javadoc of
EntityManager.detach
states:So you're persisting it, then detaching it. But the operations associated to persist have not been flushed yet, and the entity is thus not saved to the database.
Why do you want to detach it? As soon as the transaction is ended, it will be detached automatically.
修改 JB 的答案:您也可以使用干净的标准机制,而不强制容器显式分离或刷新:
结果您将得到一个分离的实体。
Amending JB's answer: you could as well use clean, standard mechanism, without forcing the container to detach or flush explicitly:
You'll get a detached entity as a result.