Is there any way to get a reference to the attached object when using cascading on collections?
It's easiest to explain in code
Code:
The dataobjects and mapping
public class Action {
...
@OneToMany( targetEntity = ActionObjective.class, mappedBy = "action", cascade=CascadeType.ALL, orphanRemoval=true )
private Set<ActionObjective> objectives = new HashSet<ActionObjective>();
...
public void addObjective(ActionObjective objective) {
objectives.add(objective);
objective.setAction(this);
}
....
}
public class ActionObjective {
@Id
@SequenceGenerator(name="SEQ", sequenceName="SCHEMA.SEQ", allocationSize = 1 )
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ")
private Integer id;
@ManyToOne
@JoinColumn( name="ACTION_ID" )
private Action action;
}
//The business logic.
@RemotingInclude
@Transactional
public ActionObjective createObjective(final Integer actionId,
final ActionObjective clientObjective) {
// clientObjective is always a detached object
Action action = fEm.find(Action.class,actionId);
action.addObjective(clientObjective);
// .update() is a wrapper around the .merge method of hibernate
Action updated = fEm.merge( action );
fEm.flush();
// I need to be able to return the attached/persisted object that should now have and ID as the
// view needs to be informed of the objects id
// unfortunately, as this point actionObjective is not an attached object as I would assume it would be but has
// instead been copied into a new object and then persisted.
return actionObjective;
}
(note: code is simplified)
I need to be able to get a hold of the newly generated ID for the ActionObjective object. The only guaranteed unique property of two ActionObjective objects is id, so searching through the resulting collection isn't an option.
The only way I know how to accomplish this is to not use cascading, but I would prefer to not go that route unless I have no other option.