Reputation: 989
Why do I need to use a transaction to persist an Entity? Is there something I can add to my persistence.xml to auto-commit?
This doesn't insert:
em.persist(this);
But this does:
em.getTransaction().begin();
em.persist(this);
em.getTransaction().commit();
I guess my initial reference point was this GWT doco
public void persist()
{
EntityManager em = entityManager();
try
{
em.persist(this);
}
finally
{
em.close();
}
}
Upvotes: 1
Views: 5336
Reputation: 15577
JPA does not define such behaviour; any "persist()" is defined to wait til the next transaction according to the spec. Obviously some implementations of JPA (such as DataNucleus JPA) do provide that (auto-commit) facility, but it's beyond (not part of) the JPA spec
Upvotes: 1
Reputation: 9102
IMO there is no such setting in persistence.xml
I think this pattern is adopted from JDBC transaction management where you can set autocommit false on the connection and then execute any number of queries. But unless you call commit on connection the transaction will not be committed. If autocommit is false (which is default) then each executed statement is implicitly committed and we don’t want this to happen if we have multiple statements that need to run in an atomic operation.
Taking your example, when you persist the object, that object may have associations which are dirty and need to be persisted too. So there would be more than one sql that needs to run atomically. So the above mentioned transaction management strategy is used.
The entity manager (in JPA) and session API (in Hibernate) are designed to abstract the CRUD operations on database. For actually commiting the sql statements generated, transaction API has been designed as an abstraction over the transaction management. The reason for this separate abstraction I believe is that transactions are usually of two types – resource local transaction and distributed transaction.
Resource local transaction need to be handled in a different way by the transaction management infrastructure than distributed transaction. In resource local transactions all the sql sent to the database are commited by the database when a commit is called upon the connection or rolled back when rollback is called on connection. In distributed transaction management, transaction manager component is the one managing the signaling of commit or rollback to all participants.
In JPA you can mention the transaction type as
<persistence-unit transaction-type="RESOURCE_LOCAL or JTA">
.................................
</persitence-unit>
Upvotes: 1