Search code examples
javadatabasepersistenceentitymanager

Get just added Object with EntityManagerFactory


I'm developing a java app with MySql database, JPA objects and EntityManagerFactory with EclipseLink to manage the database. Everything works Ok but I have an issue.

One of my JPA objects is like this

public class JPAObject1{
     @Id
     @GeneratedValue
     private int id;
     @OneToMany(//things here)
     List<JPAObject2> list1;
     ...
 }

So the id field will be autogenerated by the EntityManagerFactory when I store it in the database. Asumming em type EntityManager and object type JPAObject1:

em.getTransaction().begin();
em.persist(object);
em.getTransaction().commit();
//house work closing things

The JPAObject1 is added correctly, I can see all fields in my database. As field id is the key to do the find operation, my question is: Is there a way to get the last added object on the EntityManager on just the moment it is added?

Because I have others objects that use the JPAObject1 id field as a foreign key and I need that field when just the object is added to the database to link the others, but the only way I know to get it is getting all the JPAObjects and getting the last one in the Collection. So, with a few Objects it won't be a problem but if one process insert on database and another do the same before process 1 does the findAll to get the last added, there will be a coherence error....

I think I've explained it well.

Thanks a lot!


Solution

  • you can use this code

    Obejct en = new Obejct ();
    en.setxxx("My name");
    em.persist(en);
    em.flush();
    System.out.println(en.getId());
    

    the id genrated after flush