Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is a standalone java application, not web application. So when I persist the object like this

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

The id inside the T t object is still null, even though a new row with correct data and id is created correctly inside the database. Usually in my web app that utilize @EJB, the id available right after I persist, since it persist the entity object into my persistence context, I am not sure if I have my persistence context here?

This is how I mapped my id inside my @Entity Class

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

also I make the id of this table in the database AUTO_INCREMENT, like this

CREATE TABLE Config
(
    ID int NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (ID)
)

This is how I obtain my EntityManager

EntityManagerFactory emf = Persistence.createEntityManagerFactory("CorePU");
em = emf.createEntityManager();

Here is what inside my persistence.xml

<persistence-unit name="CorePU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>    
<class>com.wf.docsys.core.model.Config</class>    
<properties>
  <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/XNINFODB"/>
  <property name="javax.persistence.jdbc.password" value="xxx"/>
  <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
  <property name="javax.persistence.jdbc.user" value="xxx"/>
</properties>

Please help, I am not sure what I did wrong here.

like image 977
Thang Pham Avatar asked Apr 05 '12 21:04

Thang Pham


2 Answers

Try adding a @GeneratedValue on your id field.

like image 193
barsju Avatar answered Oct 03 '22 21:10

barsju


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.

like image 30
Guedes Avatar answered Oct 03 '22 22:10

Guedes