views:

282

answers:

3

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.

A: 

Use eager initialization on your mapping.


@Basic(fetch=FetchType.EAGER)
Calendar date;

marcos
This is not what OP is asking. Plus fetching is eager by default for value properties.
ChssPly76
+2  A: 

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.

ChssPly76
A: 

What is the actual scenario? If you don't need this values to be persisted, annotate them with @Transient, and put the initalization this way:

private Calendar date = Calendar.getInstance();
Bozho