EzDevInfo.com

querydsl

Unified Queries for Java Querydsl - Unified Queries for Java querydsl

Eclipse issue with Maven build and JDK when generating Qclasses in Querydsl

When I add this code below in my pom.xml to support Querydsl

<plugin>
  <groupId>com.mysema.maven</groupId>
  <artifactId>apt-maven-plugin</artifactId>
  <version>1.0.6</version>
  <executions>
    <execution> 
      <goals>
        <goal>process</goal>
      </goals>
      <configuration>
        <outputDirectory>target/generated-sources/java</outputDirectory>
        <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
      </configuration>
    </execution>
  </executions>
</plugin>

I got this error when building with Eclipse. I think it has relation with classpath and JDK jars

You need to run build with JDK or have tools.jar on the classpath.
If this occures during eclipse build make sure you run eclipse under  JDK as well 
(com.mysema.maven:apt-maven-plugin:1.0.6:process:default:generate-sources)

.classpath :

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" output="target/classes" path="src">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v8.0">
        <attributes>
            <attribute name="owner.project.facets" value="jst.web"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
            <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="output" path="target/classes"/>
</classpath>


Extra info :

enter image description here

My maven Installation

enter image description here

JAVA_HOME : C:\Program Files\Java\jdk1.7.0_45
PATH : %JAVA_HOME%\bin;


Source: (StackOverflow)

Generating JPA2 Metamodel from a Gradle build script

I'm trying to set up a Gradle build script for a new project. That project will use JPA 2 along with Querydsl.

On the following page of Querydsl's reference documentation, they explain how to set up their JPAAnnotationProcessor (apt) for Maven and Ant.

I would like to do the same with Gradle, but I don't know how and my beloved friend did not help me much on this one. I need to find a way to invoke Javac (preferably without any additional dependencies) with arguments to be able to specify the processor that apt should use (?)


Source: (StackOverflow)

Advertisements

QueryDSL Generated classes not able to access second level elements for querying

I am using QueryDSL with Spring Data JPA in my Java Project and have Generated files using QueryDSL maven plugin to use the QueryDSL Model classes generated by it. This works great when i use it for one level nested objects, however if i try to access the 2nd level access objects it gives a NullPointerException saving the 2nd level model object is not initialized.

Would appreciate some help.

I am getting a NullPointerException in 3rd line qmachine.vendor is null.

QTransaction qtransaction = QTransaction.transaction;
QMachine qmachine = qtransaction.machine;
BooleanExpression vendorexp = qmachine.vendor.vendor.eq(machineType);

My Mapping classes are below: Transaction

@Entity
@Table(name = "dsdsd")
public class Transaction extends AbstractPersistable<Long> {

    private static final long serialVersionUID = 1L;

    @ManyToOne
    @JoinColumn(name = "machine_id")
    private Machine machine;

}

And the Machine class is :

@Entity
@Table(name="machine")
public class Machine extends AbstractPersistable<Long> {

    private static final long serialVersionUID = 1L;

    @ManyToOne
    @JoinColumn(name="vendor_id")
    private Vendor vendor;
}

and the Vendor class is

@Entity
@Table(name="vendors")
public class Vendor extends AbstractPersistable<Long> {

    private static final long serialVersionUID = 1L;

    @Column(name="vendor")
    @Enumerated(EnumType.STRING)
    private VendorType vendor;

}

I have ommitted the getters and setters intentionally.


Source: (StackOverflow)

Spring Data JPA and spring-security: filter on database level (especially for paging)

I'm trying to add method level security to my open source project using annotations and spring-security. The problem I'm now facing are findAll methods especially the ones for Paging (eg. returning a page).

Using @PostFilter works on Lists (but I personally believe its not a good idea to filter in application and not database) but completely fails on paging queries.

This is problematic because I have an Entity containing List<Compound>. There are different implementations of compound and a user might only have the privilege to read one of the Compounds. Compound uses TABLE_PER_CLASS inheritance. Repositories implement QueryDslPredicateExecutor.

My thinking is to add a predicate to each query that limits the return results based on current user. However I'm kind of lost on a) how the data model for user and roles should look and b) how to then create the predicate (this is probably easy once the model is defined). Or does querydsl already offer type based filtering (on elements contained in the queried class)?


Source: (StackOverflow)

How do I build a GenericDao using QueryDSL?

First of, I am really new to QueryDSL.

I'm using a Spring + Hibernate environment.

The problem I'm facing is with building a GenericDAO to implement all the basic CRUD operations, but I'm not sure how do I get the static reference from a QEntity.

My entity class structure looks like this:

    @Entity //jpa
    public class Entity extends AbstractEntity{
    //fields
    ...
    }

    public abstract class AbstractEntity{
    //Logger 
    }

The basic structure of a QueryDSL-generated entity

    public class QEntity extends PEntity<Entity>{
    ...
    public static final QEntity entity = new QEntity("entity");        
    ...
    //constructors

    } 

And the GenericDao would look like this:

    public class abstract GenericDao<T extends AbstractEntity, K extends PEntity<? extends AbstractEntity>>{

    //some kind of method to get the K.k (QEntity.entity) reference.        
    //CRUD operations using T and K

    }

One approach would be using Reflection, but I'm not an advocate of using that method, especially in this case.

Another thing that I'm not sure of, is it mandatory to use the static reference from a QEntity to build queries or is it ok if I do a contructor call to get a new object. Also, what does the String in the constructor parameter signify?

    public QEntity(String variable) {
    this(Entity.class, forVariable(variable), INITS);
    }

Source: (StackOverflow)

Spring-Data-JPA with QueryDslPredicateExecutor and Joining into a collection

Let's say I have a data model like this (pseudocode):

@Entity
Person {
    @OneToMany
    List<PersonAttribute> attributes;
}

@Entity
PersonAttribute {
    @ManyToOne
    AttributeName attributeName;

    String attributeValue;
}

@Entity
AttributeName {
    String name;
}

I have a Spring-Data-JPA repository defined such as:

public interface PersonRepository extends PagingAndSortingRepository<Person, Long>, QueryDslPredicateExecutor<Person>{}

I see in the QueryDSL documentation that there is a mechanism to Join from the Person to the PersonAttribute, but it looks like you need access to the QueryDsl Query object, which the client of the repository wouldn't have.

What I would like to do with my Predicate is to find all those Persons that have an AttributeValue (there's one join) with a value of "blue" and an AttributeName (there's another join) with a name of "eyecolor". I'm not sure how I would do that with an any() and enforce that I only get those with eye_color=blue and not those with shoe_color=blue.

I was hoping I could do something like this:

QPerson person = QPerson.person;
QPersonAttribute attribute = person.attributes.any();

Predicate predicate = person.name.toLowerCase().startsWith("jo")
    .and(attribute.attributeName().name.toLowerCase().eq("eye color")
          .and(attribute.attributeValue.toLowerCase().eq("blue")));

but with the any() in there it just matches anything with an attribute value of "blue" and anything with an "eye color" attribute regardless of color. How I can make those conditions apply to the same attribute within the set?


Source: (StackOverflow)

Generic code failed with Spring data and Querydsl

i use querydsl that's why i don't need method like findByName() and all my repository interface are empty.

So i try to make genric code to avoid repetitive interface with empty methods because i have many classes in my entities mapped by hibernate.

public interface GenericResposotory<T> 
              extends JpaRepository<T, Integer>, QueryDslPredicateExecutor<T> {

}

When I run my server I get this error :

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'genericResposotory': 
Invocation of init method failed; nested exception is 
java.lang.IllegalArgumentException: Not an managed type: class java.lang.Object

also there is not a way to make a generic repository like i try to do ?


Source: (StackOverflow)

Pivot-like result with JPA/QueryDSL

We are using JPA2, Spring Data and QueryDSL in our project. I have the following tables and related JPA entities:

table Person (id, ...) 

table Activity (id, type, ...)

@Entity
@Configurable
public class Activity {
   @ElementCollection
   @CollectionTable(joinColumns = @JoinColumn(name = "ACTIVITY_ID"))
   @NotEmpty
   @Valid
   private Set<ActivityName> names = new HashSet<>();

table ActivityName(activity_id, name, ...) 

@Embeddable
  @Immutable
  @Table(uniqueConstraints = @UniqueConstraint(columnNames = "NAME"))
  public static class ActivityName { ... }

table ActivityLevel(person_id, activity_id, level) 

@Entity
@Immutable
@Validated
public final class ActivityLevel{...}

1..n for Actitivy to ActivityName - an activity might have different names (e.g. running, jogging)

A person might have a certain level for a given activity and can perfom several activities (each with a defined level).

  • There should be a search with activity names (e.g. running etc.) as parameters (a list of activity names)
  • As a result all persons should be found who perform the related activity.
  • The result should contains all activities search for with their corresponding level, the person's name and the overall sum of the persons activities

Example the following data:

  • Person = (id=1, name=Bob)
  • Person = (id=2, name=Mary)
  • Activity = (1, ...)
  • Activity = (2, ...)
  • ActivityName = (activity_id=1, name ="jogging")
  • ActivityName = (activity_id=1, name = "running")
  • ActivityName = (activity_id=2, name = "dancing")
  • ActivityLevel = (person_id=1, activity_id=1, level=0.7f)
  • ActivityLevel = (person_id=1, activity_id=2, level=0.1f)
  • ActivityLevel = (person_id=2, activity_id=1, level=0.5f)

Searching for persons who are "running" or "dancing" should get a result like this:

Person[Name]   ActitiyName  ActivityLevel ActitiyName  ActivityLevel  Sum
Bob             running         0.7         dancing         0.1       0.8
Mary            running         0.5                                   0.5          

My Question: Is there a JPA QL / QueryDSL way to get such a result with one expression / projection? What I already have is a multi-step solution - selecting activity names and levels, performing the grouping and sum with Java8. If I do the grouping with querydsl, I do not get the single level entries. Vice versa, in my solution I have to perform several other steps.

Would be nice to know if this is possible just by using a query.


Source: (StackOverflow)

How to count distinct items on specific fields in QueryDSL

Edit: it turns out that JPA can't express this. The solution was to rewrite in SQL.

I'm using QueryDSL to perform an aggregate query on a JPA data set for reporting. I have no problem extracting the report data. For example:

...
query = query.groupBy(QVehicle.vehicle.make, QVehicle.vehicle.model);
return query.listDistinct(new QMakeModelReportData(
            QVehicle.vehicle.make, QVehicle.vehicle.model,
            QVehicle.vehicle.make.count()));

This produces a list of my DTO object, each of which contains a vehicle make, vehicle model, and the count of vehicles of that make model. Like this:

   Ford, Focus, 14
   Ford, Mondeo, 4
   Vauxhall, Astra, 4

But I can't work out the syntax to count the number of rows before I actually perform the query. The syntax I imagine is like this, which doesn't exist:

return query.countDistinct(QVehicle.vehicle.make, QVehicle.vehicle.model);

I've ended up with a rather inefficient option:

return query
    .listDistinct(QVehicle.vehicle.make, QVehicle.vehicle.model)
    .size();

Is there anything better?


Source: (StackOverflow)

Dynamic spring data jpa repository query with arbitrary AND clauses

I'm using Spring data jpa repositories, Got a requirement to give search feature with different fields. Entering fields before search is optional.I have 5 fields say EmployeeNumber, Name, Married,Profession and DateOfBirth.
Here i need to query only with the given values by user and other fields should be ignored.Ex,

Input : EmployeeNumber: ,Name:St,Married: ,Professsion:IT,DateOfBirth: 
Query : Select * from Employee e where Name like 'St%' and Profession like 'IT%';  

Input : EmployeeNumber:10,Name: ,Married: ,Professsion:IT,DateOfBirth:
Query : Select * from Employee e where EmployeeNumber like '10%' and Profession like 'IT%';  

So here we are considering values entered and querying. In this case, Spring data is having a limitation as mentioned in this post (Not scalable and all possible queries should be written) I'm using Querydsl, but still the problem exists as null fields should be ignored and almost all possible queries need to be developed. In this case 31 queries. what if search fields are 6,7,8... ??

What is the best approach to implement search option with optional fields ?


Source: (StackOverflow)

Spring Data JPA and QueryDSL

I'm new to Spring data JPA and am trying to understand how to best use it with QueryDSL. Without QueryDSL, I would be able to simply create any queries in my SpringData interface with an @Query annotation.

In order to have the same experience using QueryDSL, from what I can see, I need to either create my own custom repository implementation and have my repo interface extend my custom implementation interface or put all my QueryDSL queries at a service layer which wraps my repo.

In the first case, I lose the ability to use any of the SD autogenerated methods (ex: findAll(QueryDSL predicate) ) in my custom repo since I don't have access to the actual repo object, and in the second case I am putting query logic at the service layer instead of at the repo layer.

Neither solution sounds particularly attractive to me. Is there a 3rd way that is more appropriate? Or am I misunderstanding how to properly use QueryDSL and Spring Data?

Thanks!

Eric


Source: (StackOverflow)

Maven build problems with spring-data-jpa and querydsl

I've got an Eclipse Maven project for spring-data-jpa and QueryDsl.

I seem to have a problem with the maven-apt-plugin where if I do a mvn clean followed by a mvn install, it tries to "process" files that reference the QueryDsl generated files, but these generated files have not yet been built so I get multiple "cannot find symbol" errors.

If then have to do another mvn install, everything is ok as the generated files now exist.

Does this maven-apt-plugin need to process every file in my project, or can I give it a specified directory ?

Note: Im using JDK6, Eclipse Indigo, M2E 1.0.100

My POM is...

<project>
  ....
  <build>
    <plugins>
      <plugin>
        <groupId>com.mysema.maven</groupId>
        <artifactId>maven-apt-plugin</artifactId>
        <version>1.0.2</version>
        <executions>
          <execution>
            <phase>generate-sources</phase>
            <goals>
              <goal>process</goal>
            </goals>
            <configuration>
              <outputDirectory>target/generated-sources</outputDirectory>
              <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ....
</project>

Source: (StackOverflow)

Can I remove the discriminator column in a Hibernate single table inheritance?

We use single table inheritance for every table in our application. This allows different instances of the same application stack to work with the same DAOs while their entities might differ slightly potentially containing information unique to that instance. An abstract class defines the basic table structure and an extension defines additional columns, if needed by that instance:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "client")
public abstract class Client extends AbstractPersistable<Long> {
    // ...
}

application A:

@Entity
public class ClientSimple extends Client {
    private String name;
    // getter, setter
}

application B:

@Entity
public class ClientAdvanced extends Client {
    private String description;
    // getter, setter
}

Now a DAO can work with Client objects for application A and B but application B can define additional information for its client object that may be read by a manager method unique to application B:

application A:

Client client = new ClientSimple();
clientDao.save(client);

application B:

Client client = new ClientAdvanced();
clientDao.save(client);

Unfortunately this means there is a DTYPE column in every table (or any other name that I might choose). Is there any way to get rid of this? We don't need it and it's using up DB space...

Thanks!


EDIT

Important to note: @MappedSuperclass won't work. We're using QueryDSL as our HQL abstraction layer. This requires automatically generated Query Type classes for type save querying. These however will only be generated correctly if the abstract class is annotated with @Entity.

This is neccessairy because we want to query against the abstract class Client while in truth querying ClientSimple in application A and ClientAdvanced in application B:

So in any application this will work:

query.where(QClient.client.name.equals("something");

and in application B this will work:

query.where(QClientSimple.client.description.equals("something else");

EDIT2 - boil down

It seems to boil down to this: Can I configure hibernate at deploy time to set the discriminator type for an inhertited entity to a fixed value. So going with my example a Client will always be ClientSimple in one application and ClientAdvanced in the other so that I don't have to store that information in the database?

Like I said: Each application will be an instance of the base application stack. Each application might define additional columns for their local database but ALL objects will be of the same type for that instance so we guarantee that the discriminator is always the same making it redundant in the database and a use case for hibernate configuration.


Source: (StackOverflow)

Querydsl Code generation for groovy with gradle

I have entity beans defined in groovy. I'm not being able to generate querydsl code for entities in groovy.

This Gradle Querydsl Configuration works fine for entity beans in Java but not for groovy.

Referring to Querydsl documentation on Alternative code generation, it states that GenericExporter have to used to generate code for groovy entities. But I could not figure out how to configure GenericExporter in gradle.

Please share if anyone have been able to generate querydsl code for entities in groovy with gradle.

Thanks


Source: (StackOverflow)

How to add Query Hints to spring data jpa querydsl queries?

I'm using Spring Data JPA 1.7.1

I was trying pass query hints (e.g. for Hibernate query caching) to queries when using the querydsl methods of the standard Spring Data repositories, as defined in the QueryDslPredicateExecutor interface, e.g. findOne(Predicate predicate), findAll(Predicate predicate) etc.

I figured that they can be set by overriding the methods in QueryDslPredicateExecutor (in my repository interface or an intermediate interface) and adding the QueryHints annotation, but since I cannot find this documented anywhere I was wondering if this is the recommended way of doing it.

Here is an example:

public interface MyEntityRepository extends CrudRepository<MyEntity, Integer>, CacheableQueryDslPredicateExecutor<MyEntity> {

    @QueryHints(value = {
            @QueryHint(name = "org.hibernate.cacheable", value = "true"),
            @QueryHint(name = "org.hibernate.cacheMode", value = "NORMAL"),
            @QueryHint(name = "org.hibernate.cacheRegion", value = "myCacheRegion")
    })
    Iterable<T> findAll(Predicate predicate);

}

Source: (StackOverflow)