Avaje - EBean - Partial Object Query disable Lazy

2019-02-26 04:48发布

问题:

I'm developing an app using Play! Framework 2.1.3, using EBean for the model layer I wanna be able to execute a Partial Object Query and not have the un-selected properties lazy loaded on demand when I serialize to JSON in preparation to send the result back to the user.

I have tried setting AutoFetch to false, I have also tried to end the transaction before serializing to JSON (I ended up getting a Transaction is Inactive error) I've also added the annotation @Lazy(false) on my model class.

On the same note, I also have a One-to-Many association, and I wanna Query the first 3 rows of it, I used new FetchConfig().queryFirst(2) but I guess due to the same lazy loading issue, I end up getting the whole related association rows.

Looking at the manual, I read this (EBean Partial Objects):

A Partial Object will lazy load the rest of the data on demand when you get or set a property it does not have.

Is there a way around this, nothing I tried seemed to work!

回答1:

You have 2 alternatives.

Option 1) Use Ebean's built in JSON support that uses Jackson core under the hood. There are a number of writer options available from Ebean's JsonContext.

An example using PathProperties that is applied to both the query and the JSON.

PathProperties pathProperties =
        PathProperties.parse("(id,status,name,shippingAddress(id,line1,city),billingAddress(*),contacts(*))");

List<Customer> customers = Ebean.find(Customer.class)
    .apply(pathProperties)
    .findList();

String jsonString = Ebean.json().toJson(customers, pathProperties);

Option 2) is a newly available feature on version 6.2.2 where you can setDisableLazyLoading(true) on the query.

Reference: https://github.com/ebean-orm/avaje-ebeanorm/issues/360



回答2:

I have solved this issue by using the standard JDBC interface using Statements and ResultSets on the queries that I require not to have lazy loading on.

As a side note, turns out that in the case of Scala, direct field access does not use Lazy Loading, but unfortunately it is not the language I am using for my application.