java - Get WHERE clause as HQL string from Criteria or: Dynamic WHERE clause with dynamic columns in select -
i want build filter search application. however, there few restrictions. have able dynamically add conditions dynamically modify columns , joins want fetch.
i have tried using jpa repository (from spring data) specifications, , builds clause desired, have no control on columns , joins hibernate issues db.
i have tried using hibernate criteria api projections. issued query desired , had full control on selected columns , joins, clause, however, result transformation proved troublesome parsing nested objects (i tried using custom result transformer, no avail, single level object, default behaviour fine).
the "solution" have building hql string depending on case. however, have written code building clause , wondering if there way reuse (e.g. hql string predicates of spring specifications, or hibernate restrictions).
of course, if there better way that, thankful if shared.
you need use querydsl.
step 1: add com.mysema.querydsl:querydsl-apt, com.mysema.querydsl:querydsl-core , com.mysema.querydsl:querydsl-jpa dependencies project.
step 2: add @queryentity annotation entity classes on wish run dynamic queries. if queries included nested classes, add annotation nested entity classes well. example below:
@entity @queryentity @table(name = "users") public class user { @onetomany private address address; } @entity @queryentity @table(name = "address") public class address { @manytoone private country country; } @entity @queryentity @table(name = "country") public class country { } step 3: run com.mysema.maven:apt-maven-plugin maven plugin during process phase follows:
<build> <plugins> <plugin> <groupid>com.mysema.maven</groupid> <artifactid>apt-maven-plugin</artifactid> <version>1.1.1</version> <executions> <execution> <goals> <goal>process</goal> </goals> <configuration> <outputdirectory>target/generated-sources/java</outputdirectory> <processor>com.mysema.query.apt.querydslannotationprocessor</processor> </configuration> </execution> </executions> </plugin> </plugins> </build> step 4: change spring data jpa repository interface extend querydslpredicateexecutor well.
interface userrepository extends jparepository<user, long>, querydslpredicateexecutor<user> {} with set up, apt plugin generate q classes every class annotated queryentity. can generate dynamic queries using these classes. example:
quser user = quser.user; booleanexpression query = and(eq(user.active, boolean.true), eq(user.address.country.name, "belgium")); collection<user> activeusersfrombelgium = userrepository.findall(query);
Comments
Post a Comment