There are many different tools the best i think are querydsl, torpedoquery e Object Query, this three allow to write typesafe query, otherwise you can use criteria api, and if you are using jpa 2 also JPA2 Typesafe Query.
with all this tools you can build a query at runtime!!