Relational Data is Not Fetching in Ebean

ε祈祈猫儿з 提交于 2020-01-06 03:51:04

问题


Background

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.

Issue

I am currently having trouble fetching relational data completely. I have a User and a UserEmail model. The User can own multiple UserEmails.

User Model Code
User Email Model Code

When I try and fetch a User, the User data is fetched correctly, however the UserEmails are not.

Fetching Code

When I specifically add fetch("emails") to the fetch code

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));

I get This Error

Question

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?


回答1:


I have found solution to above problem. Every entity should have id.
User class has field annotated with @Id but UserEmail has not.

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;

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;


来源:https://stackoverflow.com/questions/26746989/relational-data-is-not-fetching-in-ebean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!