【问题标题】:JPA Container managed entity update after persist持久化后的 JPA 容器托管实体更新
【发布时间】:2013-02-27 21:32:45
【问题描述】:

您好,我在 JPA 中自动生成实体的主键时遇到问题。我正在保留实体并尝试从中获取 id 值,但即使我正在刷新它也会返回 null 。我正在使用最新的 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

【问题讨论】:

    标签: jpa


    【解决方案1】:

    调用flush() 会将大部分指令发送到数据库,但不会发送commit() 上生成的INSERT 命令。请参阅this question 了解更多信息。

    您似乎正在处理容器管理的事务,因此通常会在方法返回时执行提交。

    如果您想在方法内强制提交,您可以在 bean 或一个方法上禁用 CMT,并使用UserTransaction

    tx.begin();
    ...
    em.persist();
    tx.commit();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      相关资源
      最近更新 更多