javajavascriptjsonhibernatelazy-loading

How can I implement lazy initialization of the content field in the entity object?


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 example, I need to show to the user only title and creationDate, 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?


Solution

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

    It looks like the following in java:

    public class Post {
    
      ...
    
    
      PostContent postContent;
    }