Saturday, September 14, 2013

JPA Dynamic Query Builder


Dynamic Query Builder

Every time i write a JPA project i always face the need to dynamically load my entities from database without writing the HQL by myself, and for that i decided to write my own Dynamic Query Builder - DQB - which can be plugged as a jar to any new project.

this DQB will allow me to specify what to select and from what entity, it will allow to specify grouped filters, aggregation , grouping, ordering in a freindly and easy way, and after two days of coding i came up with the following DQB:

Setup

(this setup assumes you are using spring and you have an entityManager defined in your spring context), and also before we start i have to mention that this DQB is for use with simple scenarios and for unpredictable query parameters and we not to forget that JPA already have a powerful Criteria builder APIs and also there is the named queries, so this DQB is is to be used for small projects or  as a mix with above, and at the ends what we need decides what to use.

first you need to download the jar and add it to your class path
download link : DynamicQueryBuilder
the source code is also available for those who wants to toy with the jar and may need to add any feature or fix a bug.

then in your spring context xml file you need to add the following bean:


and thats it. now we are ready to use the query generator.

Obtaining QueryGenerator instance

in any part of your code you refrence your spring context and get the DQB instance like this :



The usage


lets assume we have an entity name SampleEntity :





Available Filters can be found under the package :
akab.bo3.dqb.query.filter

Other functionality :
groupBy, orderBy, aggregate

Other Links :

Source code and Sample project : SampleProject
SampleProject Libs : libs