简体   繁体   中英

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!

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

Note that the datas saved to database is a set, not list. So they don't have the order or anything like that, and you can't get the last one you've added. If you want to, pls add a column like date, time..., and the query will be like: " SELECT * FROM Table ORDER BY dateColumn DESC LIMIT 1"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM