Get list of JPA/Hibernate Persisted objects

Asked

Viewed 441 times

2

Hello, how do I get the list of persisted objects before committing it in BD. Follow the example below:

Pessoa p = new Pessoa("Joao", 21);
Pessoa p2 = new Pessoa("Pedro", 17);
Pessoa p3 = new Pessoa("Maria", 32);

//Entendo que nesse momento os dados ainda não estão salvos no banco
//Preciso obter essa lista para alterar as propriedades de alguns objetos
manager.persist(p);
manager.persist(p2);
manager.persist(p3);


//Comitando para salvar no banco
manager.getTransation().begin();
manager.getTransation().commit();
  • Your objects are in the scope of the method, why do you need their list? If you need the id generated in persistence, the method persiste returns the id.

1 answer

0


If you want the ID, you need to open the transaction before the persist. You can get the persist ID this way by using the flush():

manager.getTransation().begin();

manager.persist(p);
manager.persist(p2);
manager.persist(p3);

//depois do flush, p, p2 e p3 terão os IDs
manager.flush();

//Comitando para salvar no banco
manager.getTransation().commit();

Or, you can get their Ids after the commit:

manager.getTransation().begin();

manager.persist(p);
manager.persist(p2);
manager.persist(p3);

//Comitando para salvar no banco
manager.getTransation().commit();

//depois disto, p, p2 e p3 terão os IDs

I recommend avoiding flush usage whenever possible. If your intention is just to get the Ids, do this after the commit().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.