We have developed a framework called Querydsl
(
http://source.mysema.com/projects/querydsl-root/) which
provides the ability to write statically typed queries in native Java.
The benefits of using a fluent API for writing queries in comparison to simple strings are
* code completion in IDE
* almost none syntactically invalid queries allowed
* domain types and properties can be referenced safely
* adopts better to refactoring changes in domain types
Here some examples from a test suite where we modeled Querydsl queries after HQL (Hibernate) queries :
@Test
public void testWhere() throws Exception {
// parse( "FROM eg.mypackage.Cat qat where qat.name like
'%fluffy%' or qat.toes > 5" );
from(qat).where(qat.name.like("%fluffy
%").or(qat.toes.gt(5))).parse();
// parse( "FROM eg.mypackage.Cat qat where not qat.name like
'%fluffy%' or qat.toes > 5" );
from(qat).where(not(qat.name.like("%fluffy
%")).or(qat.toes.gt(5))).parse();
// parse( "FROM eg.mypackage.Cat qat where not qat.name not
like '%fluffy%'" );
from(qat).where(not(qat.name.like("%fluffy%"))).parse();
// parse( "FROM eg.mypackage.Cat qat where qat.name in
('crater','bean','fluffy')" );
from(qat).where(qat.name.in("crater","bean","fluffy")).parse();
// parse( "FROM eg.mypackage.Cat qat where qat.name not in
('crater','bean','fluffy')" );
from(qat).where(qat.name.notIn("crater","bean","fluffy")).parse();
// parse( "from Animal an where sqrt(an.bodyWeight)/2 > 10" );
from(an).where(div(sqrt(an.bodyWeight),2).gt(10)).parse();
// parse( "from Animal an where (an.bodyWeight > 10 and
an.bodyWeight < 100) or an.bodyWeight is null" );
from(an).where(an.bodyWeight.gt(10).and(an.bodyWeight.lt(100).or(an.bodyWeight.isnull()))).parse();
}
More examples :
http://source.mysema.com/projects/querydsl-root/xref-test/com/mysema/query/grammar/hql/HqlParserTest.html
What do you think?
Br,
Timo Westkämper