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

查看:240
本文介绍了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中class,我有一个insert方法,在这个实体上调用 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。当交易结束时,将发生刷新,因此交易之外的实体用户将在实体中看到生成的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天全站免登陆