When I have an Entity with relationships I don't know which is the best way to save changes to DB.
Here is a simplified entity. Please consider I have made little changes to the code to post it here and I can have introduced some errors.
public class Permessitemporanei implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID_permesso")
private Integer iDpermesso;
@Column(name = "Stato_permesso")
private Integer statopermesso;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "iDpermesso")
private Collection<Accessiconpermesso> accessiconpermessoCollection;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "iDpermesso")
private Ingressiconpermesso ingressiconpermesso;
As you can see it is linked to other 2 entities with a OneToMany and OneToOne relationships. I'm using Glassfish with jta so transactions and entityManagers are managed by the container.
At a time I have a detached (JPA terminology) Permessitemporanei instance in memory. I have to persist the following changes to the database: 1- the associated ingressiconpermesso must be deleted 2- a new ingressiconpermesso must be created 3- statopermesso field must be updated 4- a new Accessiconpermesso must be added to the collection accessiconpermessoCollection
Which is the best way of doing so ? Perhaps I can do all necessary changes in the Permessitemporanei instance an merge it but I had many troubles doing so and start to think it is not the right side of the relationships to persist changes. For me it more natural to save an object at a time, so eliminating all those cascade = CascadeType.ALL.
Suppose my Permessitemporanei instance is called 'permesso' ; my code is something like this:
- getEntityManager().remove(permesso.ingressiconpermesso);
- getEntityManager().persist(a new Ingressiconpermesso );
- getEntityManager().merge(permesso) // once its statopermesso field has been updated;
- getEntityManager().perist(a new Accessiconpermesso );
Obviously this way I have to manually update the in memory 'permesso' with all the changes I made on Database.
Is there a better approach ?
By the way all the JPA relationships I have seen are bidirectional. Can I make them unidirectional ? To put it in other words can I safely eliminate Code:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "iDpermesso") private Collection accessiconpermessoCollection;
from the Permessitemporanei entity preserving it on the Accessiconpermesso entity or do i break JPA ?
Thanks Filippo