Get list of persistent JPA / Hibernate objects

2

Hello, how do I get the list of persisted objects before committing it to DB. Here's 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();
    
asked by anonymous 03.03.2015 / 13:02

1 answer

0

If you want the ID, you need to open the transaction before persist. You can get the persist ID this way, using 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 using the flush whenever possible. If you just want to get the IDs, do this after commit ().

    
03.03.2015 / 13:27