Indigenuity
Indigenuity

Reputation: 9740

Best way to persist JPA entities in Play framework

I'm new to JPA, let alone JPA in Play, so I'm wondering what is the best way to save my objects with a @ManyToOne relationship to multiple classes.

The UserJump class is defined as follows:

@Entity
public class UserJump extends Model{
    @ManyToOne
    public User user;
    @ManyToOne
    public JumpSession jumpSession;
    public String parachuteUID;
    public String notes;
    public int status;

}

The relationship to UserJump is defined from inside JumpSession by :

@OneToMany(mappedBy="jumpSession")
public List<UserJump> userJumps;

Likewise in the User class:

@OneToMany(mappedBy="user")
public List<UserJump> userJumps;

Here's how I'm saving things right now:

JumpSession jumpSession = new JumpSession();
//...Code here to fill in jumpSession...
jumpSession.save();

UserJump userJump;
for(String jumperUID : jumpers)
{
    userJump = new UserJump();
    userJump.jumpSession = jumpSession;
    userJump.user = User.findById(jumperUID);
    userJump.status = 1;
    userJump.save();
}

It seems to me that there should be a way to save those UserJump objects in a List called userJumps and then do jumpSession.userJumps = userJumps, then jumpSession.save() and it should persist all the UserJump objects. Is there a way to do this? And which way is the best way to do this?

Upvotes: 1

Views: 1303

Answers (1)

axtavt
axtavt

Reputation: 242726

Yes, you can cascade save from JumpSession to UserJump by setting an appropriate cascading option:

@OneToMany(mappedBy="jumpSession", cascade = CascadeType.PERSIST) 
public List<UserJump> userJumps;

Also, I don't think it's a good idea to make relationship from UserJump to User bidirectional. In the case of JumpSession it's fine since UserJumps can be treated as parts of JumpSession (for example, they are saved along with the JumpSession). But in the case of User it doesn't make sense, so that I recommend you to remove userJumps field from User. When you need UserJump for particular User, make an explicit query instead.

More on the last point. I think that number of UserJumps per JumpSession is likely to be bounded, whereas number of UserJumps per User is potentially unbounded. It means that UserJumps of User should be displayed with some kind of pagination, that makes userJumps field useless.

So, considering complications introduced by to-many relationships (Deterring “ToMany” Relationships in JPA models, Hibernate mapped collections performance problems ) I think it would be better to remove this field altogether.

Upvotes: 3

Related Questions