Is it possible to dynamically trigger calling of the @PostLoad method only on demand
Env: JBoss Seam, JPA, Hibernate
We use the @PostLoad annotation to dynamically initializ开发者_开发技巧e some of the transient variables in our @Entity (sometimes this involves looking up the parent entity to initialize status - which is a costly operation).
But under certain circumstances, we don't want this @PostLoad to get triggered, since we will not rely on the transient variables.
Is there a way to control the data dynamically post load.
One way to solve this issue, is to call this method only on demand (i.e. by removing the @PostLoad annotation and manually calling this method), but this is also error prone.
Are there any other ways to resolve this issue.
But under certain circumstances, we don't want this @PostLoad to get triggered, since we will not rely on the transient variables.
Create two entities, one with the @PostLoad
and the transient fields, and one "lighter" without.
Haven't dealt with this in java but came across similar thing in kotlin + maven + spring project.
Understanding how @PostLoad works?
@PostLoad
is called after fetching data using entity manager methods find()
or refresh()
operations is triggered to the database.
Scenario when it fails to trigger @PostLoad :
Suppose, a parent
entity had this @transient variable
which is initialised using a @PostLoad
method. And also, you had a child entity which had mapping to this parent entity.
When you retrieve a child
the find will load and persistence context is generated. Down the line when you tried to access parent content then another find is triggered. But this won't trigger the @PostLoad
method of parent
because the operation is triggered from the existing context.
Which would generally throw the uninitialized errors.
Solution
In the above scenario, I don't really need multiple entities. As I knew this behaviour. I would create an entity class method for parent
to dynamically load the contents for the respective transient variable or even set some defaults for a special scenario. And trigger or manage this method in the converter methods or where-ever the use case is.
精彩评论