Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate post initialization

I would like to initialize class members of a persisted object as soon as Hibernate loads the object from the database.

How can I do this ?

More specifically: In the following persisted object, I would like to initialize date's timezone

class Schedule {

    Calendar date
    TimeZone tz;

}

I cant do this in the constructor because hibernate will use setters to initialize the object. I cant do this in the setters because I cannot rely on the order of initialization.

like image 643
Vish Avatar asked Nov 05 '09 13:11

Vish


People also ask

What does Hibernate initialize?

next difference is that Hibernate. initialize generates and executes additional sql for fetching data. So you can use it after session is closed. When you use Eager fetch in entity it's always fetch that collections during finding data (under the connection session ) in database, but not after it.

How to initialize proxy in Hibernate?

Hibernate. initialize(entity. getXXX()) will force the initialization of a proxy entity or collection entity. getXXX() as long as the Session is still open.

What is Hibernate n1 problem?

Hibernate N+1 problem occurs when you use FetchType. LAZY for your entity associations. If you perform a query to select n-entities and if you try to call any access method of your entity's lazy association, Hibernate will perform n-additional queries to load lazily fetched objects.

How can I get all data from a table in Hibernate?

JPQL provides a simple and straightforward way to get all entities from a table. Our Hibernate session's createQuery() method receives a typed query string as the first argument and the entity's type as the second. We execute the query with a call to the getResultList() method which returns the results as a typed List.


1 Answers

You need to register a post-load event listener; it will be called after your object is loaded so you can do whatever post-processing is necessary.

If you're using JPA (Hibernate EntityManager), you can simply write a method and annotate it with @PostLoad.

Otherwise, for core Hibernate you'll need to implement a PostLoadEventListener and declare it in your configuration.

like image 87
ChssPly76 Avatar answered Sep 28 '22 01:09

ChssPly76