java - Ebean/Play Framework 关系未更新

标签 java playframework ebean

我正在使用带有 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/

相关文章:

java - 如何检测页面中是否包含句子(模糊)?

java - 将 Runnable 转换为 Supplier

java - 如何从对象的方法外部访问对象

java - 继续玩框架 - 我在这里犯了什么愚蠢的错误?

java - 无法使用 play 连接到数据库 ebean

java - 如何在同一个实体类上进行单向一对多关系?

java - 如何将重复元组列表转换为唯一元组列表?

java - 如何在 Visual Studio Code + java 上调试 play Framework 1.x 应用程序

json - 在反序列化为案例类模型之前对 JSON 进行条件过滤

java - 数据库 'default' 需要进化!当尝试使用 play Framework 2.7.0 和 Ebean 连接到 MySQL 时