Relational Data is Not Fetching in Ebean

2019-08-08 02:33发布

问题:

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;