Ebean / Play Framework关系未更新

时间:2014-08-31 13:29:25

标签: java playframework ebean

我使用Play框架2.3.3与Ebean和Java。 我有以下模型(我实现了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);

问题在于,尽管在数据库中创建了用户和跟随,但第二个和第三个断言都失败了(也就是说,用户没有任何跟随)。 我试图首先创建用户,然后是关注,但它仍然无法正常工作。

1 个答案:

答案 0 :(得分:1)

解决。似乎解决方案是在实体Follow中创建一个ID字段。 我试图将两个字段都设为id,但Ebean不接受它,所以我最终使用了long类型的id。