JPA(EBeans)关系错误

时间:2014-05-04 19:57:09

标签: html jpa playframework entity ebean

首先,我正在使用Play框架2.2.2编写一个使用Ebeans的Web应用程序。 我将从代码开始,因为这样可以更容易地解释我的问题:

这是我的模特之一:

@Entity
public class Topic extends Model {

    @Id
    private String title;
    private String description;
    @ManyToOne
    private User createdBy;
    private Integer popular;
    @Formats.DateTime(pattern="dd/MM/yyyy")
    private Date created;
    private boolean over18;
    @ManyToMany(cascade = CascadeType.REMOVE)
    private List<Tag> tags;
}

模型有这种方法:

/**
 * Return the number of opinions that exist on a specific Topic
 */
public int countOpinions() {
    return Opinion.find.where().eq("topic", this).findRowCount();
}

这是我的第二个相关模型:

@Entity
public class Opinion extends Model {

    @Id
    private Long opinionId;
    @Constraints.Pattern("pos|neg|neut")
    private String type;
    @ManyToOne
    private Topic topic;
    @ManyToOne
    private User user;
    private int rating;
    private String text;
    private boolean reported;
        @ManyToOne
        private Opinion parent;
}

包含此静态方法

public static Model.Finder<Long, Opinion> find = new Model.Finder<Long, Opinion>(Long.class, Opinion.class);

这里我们有HTML中的调用

        @topics.map { topic =>
            <th scope="col" id="name">@topic.getTitle()</th>
            <th scope="col" id="description">@topic.getDescription()</th>
            <th scope="col" id="opinions">@topic.countOpinions()</th>
        }

问题:

好的,所以countOpinions()无法正常工作。我创建了一些测试值,它应该显示特定测试主题的值2,但它显示值0.我不确定Ebeans如何使用我为自己创建的类型保存这些字段,但afaik它应该像这样工作。

我已经尝试过覆盖模型中的equals方法,因为我认为它可能会被使用,但显然它不是。

每次帮助都是如此。

1 个答案:

答案 0 :(得分:1)

我快速测试了,效果很好

private FakeApplication fakeApplication;

@Before
public void setup() {
    fakeApplication = fakeApplication(inMemoryDatabase());
    start(fakeApplication);
}

@After
public void tearDown() {
    stop(fakeApplication);
}

@Test
public void countOpinionsTest() {
    // given
    Topic topic = new Topic();
    topic.setTitle("test");
    topic.save();
    Opinion opinion1 = new Opinion();
    opinion1.setOpinionId((long) 1);
    opinion1.save();
    Opinion opinion2 = new Opinion();
    opinion2.setOpinionId((long) 2);
    opinion2.save();
    // when
    opinion1.setTopic(topic);
    opinion1.update();
    opinion2.setTopic(topic);
    opinion2.update();
    // then
    assertThat(topic.countOpinions()).isEqualTo(2);
}

你有你的ebean配置集和相应包中的实体(这里是模型)吗?

db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
ebean.default="models.*" 
相关问题