JPA: How to get Id after persist in standalone java app

旧巷老猫 提交于 2019-12-05 16:10:13

Try adding a @GeneratedValue on your id field.

As I found on this post the EntityManager have a method called refresh that will update your object after you persist him.

So your code will probably looks like this:

public <T> T create(T t) {
    em.getTransaction().begin();
    em.persist(t);
    em.refresh(t);
    em.flush();
    em.getTransaction().commit();
    return t;
}

I haven't tested this, so I'm not sure where exactly to put the refresh method call, there, after the commit, after the flush, etc.

Hope it can help you.

Good luck.

I know it's not a persist but the merge will do the same thing more simply. I wrap my persist in an actual merge operation which will save the entity if it does not exist.

public T persist(T obj) {
    EntityManager em = ThreadLocalPersistenceManager.getEntityManager();

    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        obj = em.merge(obj);
    } finally {
        if (! tx.getRollbackOnly()) {
            tx.commit();
        }
    }

    return obj;
}


/**
 * This will save the object and return the id of the persisted object.
 *  
 * @param obj
 * @return The id of the persisted object.
 */
public Long save(T obj) {
    persist(obj);
    return obj.getId();
}

Here is my answer. Tested

When mapping your Id, switch from what I have above, which is

@Id
@Basic(optional = false)
@Column(name = "ID")
private Long id;

to

@Entity
public class Person {
   @Id
   @TableGenerator(name="TABLE_GEN", table="SEQUENCE_TABLE", pkColumnName="SEQ_NAME",
       valueColumnName="SEQ_COUNT", pkColumnValue="PERSON_SEQ")
   @GeneratedValue(strategy=GenerationType.TABLE, generator="TABLE_GEN")
   private long id;
   ...
}

Since I use microsoft SQL server, I have to use @TableGenerator. More information can be found here http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Table_sequencing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!