I'm learning persistence in Java following some tutorial.
I'm using Java EE 7 and Payara server.
I noticed that each uses a different method for persistence.
Examples:
simple
@Stateless public class BookServiceBean implements BookService { @PersistenceContext private EntityManager em; public void createOrUpdate(Book book) { em.persist(book); } public void remove(Book book) { em.remove(book); } }
with
flush()
, this is used when validation strategy isn't set on "AUTO" in persistene.xml, right?@Stateless public class BookServiceBean implements BookService { @PersistenceContext private EntityManager em; public void createOrUpdate(Book book) { em.persist(book); em.flush(); } public void remove(Book book) { em.remove(book); em.flush(); } }
with transaction
@Stateless public class BookServiceBean implements BookService { @PersistenceContext private EntityManager em; public void createOrUpdate(Book book) { utx.begin(); em.persist(book); utx.commit(); } public void remove(Book book) { utx.begin(); em.remove(book); utx.commit(); } }
When and why do I have to use the last one?
Is it necessary to use em.close()
at the end of each method?
What are the good practices?