I have a unidirectional relation Project -> ProjectType
:
@Entity
public class Project extends NamedEntity
{
@ManyToOne(optional = false)
@JoinColumn(name = "TYPE_ID")
private ProjectType type;
}
@Entity
public class ProjectType extends Lookup
{
@Min(0)
private int progressive = 1;
}
Note that there's no cascade.
Now, when I insert a new Project I need to increment the type progressive.
This is what I'm doing inside an EJB, but I'm not sure it's the best approach:
public void create(Project project)
{
em.persist(project);
/* is necessary to merge the type? */
ProjectType type = em.merge(project.getType());
/* is necessary to set the type again? */
project.setType(type);
int progressive = type.getProgressive();
type.setProgressive(progressive + 1);
project.setCode(type.getPrefix() + progressive);
}
I'm using eclipselink 2.6.0, but I'd like to know if there's a implementation independent best practice and/or if there are behavioral differences between persistence providers, about this specific scenario.
UPDATE
to clarify the context when entering EJB create method (it is invoked by a JSF @ManagedBean
):
project.projectType
is DETACHEDproject
is NEW- no transaction (I'm using JTA/CMT) is active
I am not asking about the difference between persist()
and merge()
, I'm asking if either
- if
em.persist(project)
automatically "reattach"project.projectType
(I suppose not) - if it is legal the call order: first
em.persist(project)
thenem.merge(projectType)
or if it should be inverted - since
em.merge(projectType)
returns a different instance, if it is required to callproject.setType(managedProjectType)
An explaination of "why" this works in a way and not in another is also welcome.