Jan 9th, 2010, 03:31 PM
Externalize Queries (Hibernate/Spring)
I'm searching for a way to externalize queries and already found a few solutions however I'm not really happy with the solutions. I'm using hibernate and hibernate annotations. Currently i have parked the queries in the entity objects of my domain model as if hibernate scans the objects for queries it only picks up the queries from the files that contain entities. However I feel that the queries should be either stored in the Repository classes as thats the place where I use the queries or should be externalized at all as this would make it possible to modify the queries (at least parts of it - e.g. simple modifications in the where clause where there are no bind values required).
I have collected the following so far:
(1) As I'm using annotations I thougth it might be possible to externalize the strings used in the annotations but I guess this is not possible as the Strings used in the annotations (@NamedQuery) have to be available at compile time.
(2) I could put the queries into a package-info.java class and use the org.springframework.orm.hibernate3.annotation.Anno tationSessionFactoryBean to load the annotations however this only works with the hibernate @NamedQuery annotations and not with the JPA variation of this annotation
(3) I guess I could also use a mixture of annotations and hbm files and put the named queries in the HBM files and add hibernate.archive.autodetection with a value of "class,hbm" in persistence.xml
So my questions are...
(1) Where do you store usually your queries?
(2) Whats the best way to store them when using hiberante annotations and spring? (externalize completely, in the code as named queries, etc.)?
Jan 10th, 2010, 05:55 AM
Personally I don`t like to externalize HQL/SQL queries. In the most cases, the DAO method local variable or class instance variable should contain the query string.
But, if you have lots and lots of complicated & changing queries, you could externalize them into properties-file with PropertyPlaceholderConfigurer or inject them as String instance variables.
Ibatis could be option also: http://ibatis.apache.org/
Jan 11th, 2010, 09:43 AM
The easiest way is to put named queries in your persistense.xml file, but keep entity mappings in annotations.
Originally Posted by wdorninger
Jan 26th, 2010, 12:04 AM
I was looking for the same answer couple weeks back...and now I have them in the HBM files. I like this solution because it lets me have multiple files with different queries for different area of the app (grouping)....code looks better to (easier to debug)... One problem I found is when developing I need to restart my server to see any changes done in the HBM file. One solution is to use JRebel....which I am trying out....if this works...I am 100% happy until there is a better solution!!
Tags for this Thread