Paulius Matulionis
Paulius Matulionis

Reputation: 23413

getGeneratedKeys in EJB

I want to get the id of persisted object. I am using EJB 3.1.

I were using prepared statement to do this and it worked perfectly.

ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
    myId = generatedKeys.getLong(1);
}

I have been searching but found nothing said how to make this work in EJB. Here is my method used to persist object to database:

public void create(T entity) {
    getEntityManager().persist(entity);
    //Something to return entity's id???
}

The persistence provider I am using is:

org.eclipse.persistence.jpa.PersistenceProvider

Upvotes: 2

Views: 157

Answers (1)

tibtof
tibtof

Reputation: 7957

Try this:

public [id_type] create(T entity) {
    getEntityManager().persist(entity);
    getEntityManager().flush();
    getEntityManager().refresh(entity);
    return entity.getId();
}

Upvotes: 2

Related Questions