« | »

Spring Bean Instantiation for JPA/Hibernate

21. August 2009

In my last project I ran into an “actually” quite obvious trouble I want to resolve properly once and for all times, because I expect it to be a regular requirement when working with something like JPA/Hibernate persistence layer and something like the Spring Framework Bean Instantiation mechanism.

When I persist some JPA mapped Entity into my database, I’d later on very much like to be able to recover it exactly in the state when it was persisted. This is what persistence is all about anyway, isn’t it? It is, but troubles arise when this persisted Entity originally was instantiated based on some Spring Prototype Bean Configuration. Typically, Parts of the Properties of such a prepopulated Beans are just for Configuration Purposes and to persist those Properties to the Database is either obsolete and causing a lot of redundant and performance burdening data (in case of e.g. simple configuration values or beans), but can also turn out to be difficult or impossible to achieve in case the injected Data (e.g. some Configuration carrying Singleton Bean) is just not made to be persistent.

However, later on, when recovering such an Entity from the Database it will have lost all it (non-persistent) configuration data. Of course: JPA/Hibernate constructs the Java Objects via the Default Constructor of the Class and populates it with the Property Values persisted in the Database. That’s it, basically. The solution for my issue should be easy and some instructions and/or even ready code should be obtainable via the Internet: I just have to “teach” Hibernate to construct the Java Objects derived as Database Entities not via the default Class Constructur but via the Spring Bean Instantiation. I “just” have to do some research about this… ;-)

Once having this in place, I expect such an approach to turn out to make very good sense for almost all persistent Entities, also for the simple cases, because it allows

  • To externalize the configuration of transient-only Property values with default (prepopulated) values becoming persistent later on and to have all this transparent in one place within the Spring Prototype Bean Configuration.
  • Domain specific Object Models to carry some (e.g. DAO aware) lookup or logic methods in case applicable and useful.

I’m eager to see it working soon!

(This post is part of my thoughts about A portfolio for Enterprise Web Applications)

« I18n aware, A/N sortable persistent labels | JPA Database Import/Export Mechanism »

The URL to TrackBack this entry is: http://developing.schimak.at/2009/08/spring-bean-instantiation-for-jpa-hibernate/trackback/

Leave a comment