我正在使用带有 Ebean 和 Java 的游戏框架 2.3.3。 我有以下模型(我实现了 getter 和 setter):
@Entity
public class Follow {
@ManyToOne
private User follower;
@ManyToOne
private User followed;
}
和
@Entity
public class User {
@Id
@GeneratedValue
private long id;
@OneToMany(mappedBy = "followed")
private Set<Follow> followers;
@OneToMany(mappedBy = "follower")
private Set<Follow> following;
public void addFollowing(Follow f) { following.add(f); }
public void addFollower(Follow f) { followers.add(f); }
}
为了测试这种关系,我有:
@Test
public void userFollowTest() {
User a = new User();
User b = new User();
Follow follow = new Follow(a, b); // a follows b
a.addFollowing(follow);
b.addFollower(follow);
Ebean.beginTransaction();
Ebean.save(a);
Ebean.save(b);
Ebean.save(follow);
Ebean.commitTransaction();
Assert.assertEquals("Number of users", 2, User.find.all().size());
Assert.assertEquals("Number of following of user A", 1, User.find.byId(1L).getFollowing().size());
Assert.assertEquals("Number of followers of user B", 1, User.find.byId(2L).getFollowers().size());
Assert.assertEquals("Number of follows", 1, Follow.find.all().size());
}
但这行得通:
Assert.assertEquals("Number of users", 2, User.find.all().size());
Assert.assertEquals("Number of following of user A", 1, a.getFollowing().size());
Assert.assertEquals("Number of followers of user B", 1, b.getFollowers().size());
Assert.assertEquals("Number of follows", 1, Follow.find.all().size());
Assert.assertTrue("User a is follower and User b is followed", follow.getFollower().getId() == 1 &&
follow.getFollowed().getId() == 2);
问题是,尽管在数据库中创建了用户和关注者,但第二个和第三个断言失败了(即,用户没有任何关注者)。 我尝试先创建用户,然后再创建关注,但仍然无法正常工作。
最佳答案
已解决。看来解决方法是在实体Follow中创建一个ID字段。 我尝试将这两个字段都作为 ID,但 Ebean 不接受它,所以我最终使用了 long 类型的 ID。
关于java - Ebean/Play Framework 关系未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25592441/