Lazy loading of the content

2019-08-04 04:31发布

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?

2条回答
Ridiculous、
2楼-- · 2019-08-04 04:53

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.

查看更多
Animai°情兽
3楼-- · 2019-08-04 04:57

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

It looks like the following in java:

public class Post {

  ...


  PostContent postContent;
}
查看更多
登录 后发表回答