JPA - 在persist()之后返回一个自动生成的id [英] JPA - Returning an auto generated id after persist()

查看:26
本文介绍了JPA - 在persist()之后返回一个自动生成的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JPA (EclipseLink) 和 Spring.假设我有一个带有自动生成 ID 的简单实体:

I'm using JPA (EclipseLink) and Spring. Say I have a simple entity with an auto-generated ID:

@Entity
public class ABC implements Serializable {
     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int id;

     // ...
}

在我的 DAO 类中,我有一个在该实体上调用 persist() 的插入方法.我希望该方法返回为新实体生成的 ID,但是当我测试它时,它返回 0.

In my DAO class, I have an insert method that calls persist() on this entity. I want the method to return the generated ID for the new entity, but when I test it, it returns 0 instead.

public class ABCDao {
    @PersistenceContext
    EntityManager em;

    @Transactional(readOnly=false)
    public int insertABC(ABC abc) {
         em.persist(abc);
         // I WANT TO RETURN THE AUTO-GENERATED ID OF abc
         // HOW CAN I DO IT?
         return abc.id; // ???
    }
}

我还有一个包装 DAO 的服务类,如果这有区别的话:

I also have a service class that wraps the DAO, if that makes a difference:

public class ABCService {
    @Resource(name="ABCDao")
    ABCDao abcDao;

    public int addNewABC(ABC abc) {
         return abcDao.insertABC(abc);
    }
}

推荐答案

ID 只保证在刷新时生成.持久化一个实体只会让它附加"到持久化上下文.因此,要么明确刷新实体管理器:

The ID is only guaranteed to be generated at flush time. Persisting an entity only makes it "attached" to the persistence context. So, either flush the entity manager explicitely:

em.persist(abc);
em.flush();
return abc.getId();

或返回实体本身而不是其 ID.当交易结束时,flush就会发生,交易外实体的用户将因此在实体中看到生成的ID.

or return the entity itself rather than its ID. When the transaction ends, the flush will happen, and users of the entity outside of the transaction will thus see the generated ID in the entity.

@Override
public ABC addNewABC(ABC abc) {
    abcDao.insertABC(abc);
    return abc;
}

这篇关于JPA - 在persist()之后返回一个自动生成的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆