Reputation: 1556
I'm reading JPA 2.1 specification and there is this fragment:
A new entity instance becomes both managed and persistent by invoking the persist method on it or by cascading the persist operation. The semantics of the persist operation, applied to an entity X are as follows: ...
Is it possible to invoke persist operation without explicitly invoking persist() method or persist operation always have to be a trigger by calling persist() ?
Let's say I have two entities A, and B, where A has OneToMany(cascade=PERSIST)
relationship with B.
Is
tx.begin();
A a = new A();
B b = new B();
a.getBCollection().add(b);
entityManager.persist(a);
tx.commit();
the same as:
tx.begin();
A a = new A();
entityManager.persist(a);
B b = new B();
a.getBCollection().add(b);
tx.commit();
In the second example will the B entity be persisted (persist operation will be cascaded) even if the entity is added after calling persist() method? Or I have to add the B entity to collection before calling persist() method like in first example and only then the persist operation will be cascaded?
And what about #3 example with two transactions:
tx1.begin();
A a = new A();
entityManager.persist(a); //persist with key 1L
tx1.commit();
tx2.begin()
B b = new B();
A a = entityManager.find(A.class, 1L);
a.getBCollection().add(b);
tx2.commit();
There is no call of persist() method in second transaction, but A is in managed state, so will the B entity be persisted?
Upvotes: 2
Views: 270
Reputation: 23562
From the JPA specification, section 3.2.4 (excerpt):
The semantics of the flush operation, applied to an entity X are as follows:
- If X is a managed entity, it is synchronized to the database.
- For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y
So, the answer is yes, b
is persisted in all your examples by cascading the PERSIST
operation to it from a
at flush time.
Upvotes: 1