简体   繁体   中英

Lazy loading of the content

I have two entities : User and Post (relation one-to-many). Post fields: id , creationDate , title , content , user .

Data is stored in the database and accessed via Hibernate.

I have a controller to pass Post object as a JSON to JavaScript. Then it is shown on the web page. But it is not always necessary to pass all the Post fields. For ex., I need to show to the user only title and creation date, and if the user presses the button Show content , only then I need to show post content (which I want to request from server only when it is need to show).

So here is a problem: How can I implement lazy initialization of the content field in Post object? Should I write two methods in my controller: one for generating JSON with list of Posts and setting content field to null or empty String , and another to pass only content string?

Make post content an object and a single table in db.

It looks like the following in java:

public class Post {

  ...


  PostContent postContent;
}

First you may try to initialize the lazy collection at the DAO via Hibernate.initialize(lazyCollection) . If it didn't work then either use FetchType.EAGER or keep the session open during request and the collection should be fetched when needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM