我是 JPA 的新手,更不用说 Play 中的 JPA 了,所以我想知道用与多个类的 @ManyToOne
关系保存我的对象的最佳方法是什么。
UserJump类定义如下:
@Entity
public class UserJump extends Model{
@ManyToOne
public User user;
@ManyToOne
public JumpSession jumpSession;
public String parachuteUID;
public String notes;
public int status;
与 UserJump 的关系是从 JumpSession 内部定义的:
@OneToMany(mappedBy="jumpSession")
public List<UserJump> userJumps;
同样在 User 类中:
@OneToMany(mappedBy="user")
public List<UserJump> userJumps;
以下是我现在的保存方式:
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();
}
在我看来,应该有一种方法可以将这些 UserJump 对象保存在名为 userJumps 的列表中,然后执行 jumpSession.userJumps = userJumps
,然后 jumpSession.save()
并且它应该保留所有 UserJump 对象。有没有办法做到这一点?哪种方法是最好的方法?
最佳答案
是的,您可以通过设置适当的级联选项将保存从 JumpSession
级联到 UserJump
:
@OneToMany(mappedBy="jumpSession", cascade = CascadeType.PERSIST)
public List<UserJump> userJumps;
另外,我不认为建立从 UserJump
到 User
的双向关系是个好主意。在 JumpSession
的情况下很好,因为 UserJump
可以被视为 JumpSession
的一部分(例如,它们与 一起保存>JumpSession
).但是在 User
的情况下它没有意义,所以我建议您从 User
中删除 userJumps
字段。当您需要针对特定 User
的 UserJump
时,请改为进行显式查询。
更多关于最后一点。我认为每个 JumpSession
的 UserJump
数量可能是有限的,而每个 User
的 UserJump
数量可能是无限的。这意味着 User
的 UserJump
应该以某种分页显示,这使得 userJumps
字段无用。
因此,考虑到由一对多关系(Deterring “ToMany” Relationships in JPA models、Hibernate mapped collections performance problems )引入的复杂性,我认为最好完全删除该字段。
关于mysql - 在 Play 框架中持久保存 JPA 实体的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8477358/