1

I'm trying to fetch just a part of the model using Ebean in Play! Framework, but I'm having some problems and I didn't found any solutions.

I have these models:

User:

@Entity
@Table(name = "users")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User extends Model{
    @Id
    private int id;
    @NotNull
    @Column(name = "first_name", nullable = false)
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @NotNull
    @Column(nullable = false)
    private String username;
    @NotNull
    @Column(nullable = false)
    private String email;
    private String gender;
    private String locale;
    private Date birthday;
    private String bio;
    @NotNull
    @Column(nullable = false)
    private boolean active;
    private String avatar;
    @Column(name = "created_at",nullable = false)
    private Date createdAt;

    @OneToMany
    private List<UserToken> userTokens;

    // Getters and Setters omitted for brevity
}

UserToken:

@Entity
@Table(name = "user_tokens")
public class UserToken extends Model {
    @Id
    private int id;
    @Column(name = "user_id")
    private int userId;
    private String token;
    @Column(name = "created_at")
    @CreatedTimestamp
    private Date createdAt;

    @ManyToOne
    private User user;

    // Getters and Setters omitted for brevity
}

And then, I have a controller UserController:

public class UserController extends Controller{
    public static Result list(){
        User user = Ebean.find(User.class).select("firstName").where().idEq(1).findUnique();
        return Results.ok(Json.toJson(user));
    }
}

I expected that, when using the .select(), it would filter the fields and load a partial object, but it loads it entirely. In the logs, there is more problems that I don't know why its happening.

Statements logs

It is making 3 queries. First is the one that I want. And then it makes one to fetch the whole Model, and another one to find the UserTokens. I don't know why it is doing these last two queries and I wanted just the first one to be executed.

Solution Edit

After already accepted the fact that I would have to build the Json as suggested by @biesior , I found (out of nowhere) the solution!

public static Result list() throws JsonProcessingException {
    User user = Ebean.find(User.class).select("firstName").where().idEq(1).findUnique();
    JsonContext jc = Ebean.createJsonContext();
    return Results.ok(jc.toJsonString(user));
}

I render only the wanted fields selected in .select() after using JsonContext.

2 Answers 2

1

That's simple, when you using select("...") it always gets just id field (cannot be avoided - it's required for mapping) + desired fields, but if later you are trying to access the field that wasn't available in first select("...") - Ebean repeats the query and maps whole object.

In other words, you are accessing somewhere the field that wasn't available in first query, analyze your controller and/or templates, find all fields and add it to your select (even if i.e. they're commented with common HTML comment in the view!)

6
  • First of all, thanks for the response. Well, I saw it doing that when I was explicit calling user.getLastName() while I'm just selecting firstName, but in this case after I select, I just render the json, so I don't know why it's querying again. There is no view or something, it ends in this return Results.ok(Json.toJson(user));. Unless this Results.ok() do something under the hood.. Sep 28, 2015 at 14:42
  • yeah see this answer stackoverflow.com/a/14717035/1066240 maybe it's not most comfortable, anyway gives you full flexibility (as you can add any number of inner classes for different scenarios)
    – biesior
    Sep 28, 2015 at 14:48
  • I see.. I thought about something like that, but I wasn't doing that because of one though: Considering that I only need one field of the model, then I can make one query clean an thin to get just that field. But using these builder method, I would have to query all fields from the database and then filtering in the Java code. On large scale it wouldn't be heavier for the DB to query a lot of fields and relations considering that I just need some of them? Sep 28, 2015 at 14:54
  • I'm just trying to say, that it probably will be better if you'll make exact query and then will create JSON yourself, actually in case when you need only several simpole fields, that's enough if you'll use an Array, Map or Array of Maps for this for an example
    – biesior
    Sep 28, 2015 at 15:10
  • I will try that. But I understood why it's making those "extra" queries. Thanks for the attention. Sep 28, 2015 at 15:12
1

In the last version of Play Framework (2.6) the proper way to do this is:

   public Result list() {
        JsonContext json = ebeanServer.json();

        List<MyClass> orders= ebeanServer.find(MyClass.class).select("id,property1,property2").findList();

        return ok(json.toJson(orders));
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.