关系数据不是在Ebean中获取 [英] Relational Data is Not Fetching in Ebean
问题描述
我使用 Play Framework (Java)来存储数据。 Play Framework使用 Ebean 将类转换为可存储在数据库中的数据。
I am using Play Framework(Java) to store data. Play Framework uses Ebean to convert classes into data that can be stored in a a database.
我目前无法完全撷取关系资料。我有一个用户
和一个 UserEmail
模型。 用户
可以拥有多个 UserEmail
。
I am currently having trouble fetching relational data completely. I have a User
and a UserEmail
model. The User
can own multiple UserEmail
s.
当我尝试并获取用户
,用户
数据被正确读取,但 UserEmail
s不是。
When I try and fetch a User
, the User
data is fetched correctly, however the UserEmail
s are not.
获取代码
< br>
当我特别添加 fetch(emails)
到获取代码
User.find.fetch("emails").where().eq("userId", testUserId).findUnique();
它接缝像至少获取电子邮件。但是当我尝试通过
It seams like it at least gets the emails. However when I try and show them via
return ok(Json.toJson(retrievedTestUser));
我得到此错误
有一些方法可以让Play Framework / Ebean自动获取电子邮件,而不向每个查询添加 fetch(电子邮件)
?可能是注释?
Is there some way I can make Play Framework/Ebean automatically fetch the emails without adding fetch("emails")
to every query? Maybe an annotation?
如何解决上述错误?我得到为什么它被抛出,但我如何解决它?有什么办法让它只获取一级深吗?
How do I resolve the error above? I get why it is thrown, but how can I fix it? Is there any way to have it only fetch one level deep?
推荐答案
我找到了解决上述问题的办法。每个实体都应有id。
用户
类的字段注释为 @Id
,但 UserEmail
没有。
I have found solution to above problem. Every entity should have id.
User
class has field annotated with @Id
but UserEmail
has not.
在电子邮件
上添加 @Id
注释后 UserEmail
类用户正确抓取,其电子邮件列表不为空。
After adding @Id
annotation above email
field of UserEmail
class user is fetched properly and its email list is not empty.
@Id
public String email;
我在代码中发现的另一件事:
双向关系,那么你应该在一边使用 mappedBy
属性来表示这些是一个关系的两端而不是两个单独的关系。所以应该有:
One more thing that I spotted in your code:
When you are creating bidirectional relation then you should use mappedBy
attribute on one side to indicate that these are two ends of one relation and not two separate relations. So there should be:
@OneToMany(mappedBy="user", cascade = CascadeType.ALL)
@Constraints.Required
public List<UserEmail> emails;
这篇关于关系数据不是在Ebean中获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!