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?
First you may try to initialize the lazy collection at the DAO via
Hibernate.initialize(lazyCollection)
. If it didn't work then either useFetchType.EAGER
or keep the session open during request and the collection should be fetched when needed.Make post content an object and a single table in db.
It looks like the following in java: