Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for an HQL builder (Hibernate Query Language)

I'm looking for a builder for HQL in Java. I want to get rid of things like:

StringBuilder builder = new StringBuilder()
    .append("select stock from ")
    .append( Stock.class.getName() )
    .append( " as stock where stock.id = ")
    .append( id );

I'd rather have something like:

HqlBuilder builder = new HqlBuilder()
    .select( "stock" )
    .from( Stock.class.getName() ).as( "stock" )
    .where( "stock.id" ).equals( id );

I googled a bit, and I couldn't find one.

I wrote a quick & dumb HqlBuilder that suits my needs for now, but I'd love to find one that has more users and tests than me alone.

Note: I'd like to be able to do things like this and more, which I failed to do with the Criteria API:

select stock
from com.something.Stock as stock, com.something.Bonus as bonus
where stock.someValue = bonus.id

ie. select all stocks whose property someValue points to any bonus from the Bonus table.

Thanks!

like image 918
Sébastien RoccaSerra Avatar asked Sep 11 '08 15:09

Sébastien RoccaSerra


1 Answers

For a type-safe approach to your problem, consider Querydsl.

The example query becomes

HQLQuery query = new HibernateQuery(session);
List<Stock> s = query.from(stock, bonus)
  .where(stock.someValue.eq(bonus.id))
  .list(stock);

Querydsl uses APT for code generation like JPA2 and supports JPA/Hibernate, JDO, SQL and Java collections.

I am the maintainer of Querydsl, so this answer is biased.

like image 65
Timo Westkämper Avatar answered Oct 23 '22 12:10

Timo Westkämper