Examples

The syntax of Querydsl is similar to SQL, but the order of elements is different. Instead of the basic SELECT FROM WHERE pattern, FROM WHERE LIST is used.

Example 1

Get the cats where the name's first character is between A and B :

HQLQuery q = new HibernateQuery(session);
QCat cat = new QCat("cat"); // query type
List<Cat> cats = q.from(cat).where(cat.name.between("A", "B")).list(cat);

The related HQL query would be

select cat from Cat cat where cat.name between A and B

As you can see the Querydsl syntax resembles the underlying HQL query very much.

Example 2

Get the cats with kittens :

HQLQuery q = new HibernateQuery(session);
QCat cat = new QCat("cat");  // query type
List<Cat> cats = q.from(cat).where(cat.kittens.size().gt(0)).list(cat);

Example 3

Get the mother, mate and offspring and list them as Family instances :

HQLQuery q = new HibernateQuery(session);
QCat mother= new QCat("mother"); // query type
QCat mate= new QCat("mate");
QCat offspr= new QCat("offspr");
List<Family> families = q.from(mother).innerJoin(mother.mate, mate).leftJoin(mother.kittens, offspr)
  .list(new QFamily(mother, mate, offspr));

Alternatively you may also write this shorter as

HQLQuery q = new HibernateQuery(session);
QCat mother= new QCat("mother"); // query type
QCat offspr= new QCat("offspr");
List<Family> families = q.from(mother).leftJoin(mother.kittens, offspr)
  .list(new QFamily(mother, mother.mate;, offspr));
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.