You have there a persist operation (made with em.merge()
). Persisting a new employee does not mean that the department is also persisted (you have no cascading), so it will throw an exception because of another reason (simply try it and post the Exception).To avoid that, you either add a cascading type, or persist both of them (as you made in your example).
About your question: the only part considered would be the owning side.
In the JPA 2.0 spec, Chapter 3 Entity Operations
=> 3.2.4 Syncrhonization to the Database
is the follwoing:
Bidirectional relationships between managed entities will be persisted
based on references held by the owning side of the relationship. It is
the developer’s responsibility to keep the in-memory references held
on the owning side and those held on the inverse side consistent with
each other when they change. In the case of unidirectional one-to-one
and one-to-many relationships, it is the developer’s responsibil- ity
to insure that the semantics of the relationships are adhered to.[29]
Related to the need of a transaction: yes, you need for the merge operation an active transaction. Excerpt from JPA 2 specification:
The persist, merge, remove, and refresh methods must be invoked within
a transaction con- text when an entity manager with a
transaction-scoped persistence context is used. If there is no
transac- tion context, the
javax.persistence.TransactionRequiredException is thrown.
On how a transaction is started/how you starat a transaction: it depends on the type of the EntityManager
(on the way how you get one). In EJB it is much easier to handle that for generic situations. Also, according to the documentation of the merge method, a TransactionRequiredException is thrown, if invoked on a container-managed entity manager of type PersistenceContextType.TRANSACTION and there is no transaction
.