持久后更新JPA Container受管实体 [英] JPA Container managed entity update after persist
问题描述
您好,我在JPA中自动生成实体的主键时遇到问题.我正在坚持该实体并尝试从中获取id值,但是即使我正在执行冲洗操作,它也会返回null.我正在使用最新的glassfish,JPA,netbeans,EJB 3
Hello I am having problem with auto generated primary key of entity in JPA. I am persisting the entity and trying to get the id value out of it, but it returns null even though I am doing flush. I am using latest glassfish, JPA, netbeans, EJB 3
public class CatchesEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
(...)
@PersistenceContext(unitName = "DBF")
private EntityManager em;
(...)
public void randomMethod()
{
CatchesEntity catchEntity = new CatchesEntity();
em.persist(catchEntity);
em.flush();
System.out.println("CATCH ID: "+catchEntity.getId());
我得到NULL
推荐答案
调用flush()
会将大多数指令发送到DB,但不会发送在commit()
上生成的INSERT
命令.有关更多信息,请参见此问题.
Calling flush()
will send most instructions to the DB, but not the INSERT
commands that are generated on commit()
. See this question for more info.
您似乎正在使用容器管理的事务,因此通常在方法返回时执行提交.
You seem to be working with container-managed transactions, so in general the commit will be performed when the method returns.
如果要在方法内强制执行提交,则可以在bean或一个方法上禁用CMT并使用UserTransaction
:
If you want to force a commit inside a method, you can disable CMT either on the bean or on the one method and use a UserTransaction
:
tx.begin();
...
em.persist();
tx.commit();
这篇关于持久后更新JPA Container受管实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!