JPA need for explicit .refresh on Entity indepent of CascadeType.REFRESH?
Why isn't my CascadeType.REFRESH actually refreshing my entities? When adding an object it doesn't update the collection (still empty).
I need to explicit call entity.refresh()! Here's my partial code (where .ALL could be replaced with .REFRESH, .PERSIST):
@Entity
public class Event extends Model {
@OneToMany(mappedBy="event", cascade=CascadeType.ALL)
public List<Invitation> invitations;
}
@Entity
public class Invitation extends Model
{
@ManyToOne(cascade=CascadeType.ALL)
public Event event;
}
// ..
Event event = new Event(/* ... */);
event.save();
if (invitationid > 0)
{
开发者_开发问答 Logger.info("Invitation added to event");
Invitation invite = Invitation.findById(invitationid);
invite.event = event;
invite.save();
}
// Explicit calling this, will actually do refresh the object and show the invite.
// event.refresh();
if (event.invitations == null || event.invitations.size() == 0)
Logger.info("Still null?!");
// ..
I'm Play! framework which seems to be shipped with hibernate-jpa-2.0.
You are responsible of the coherence of the object graph. JPA won't automatically add a child to a parent's collection when you save the child. It's thus of your responsibility to do
Invitation invitation = new Invitation();
invitation.setEvent(event);
event.getInvitations().add(invitation);
It's even better to encapsulate this in a addInvitation
method of the Event
class:
public void addInvitation(invitation) {
this.invitations.add(invitation);
invitation.setEvent(this);
}
精彩评论