转载

Spring Data JPA 通过 Query DSL查询数据

昨天写 JPA的查询方式,里面关于QueryDSL的部分没有写,当时因为一直报错,现在错误解决了,补上 Spring Data JPA  通过 Query DSL 查询的实现。

另2篇地址:

Spring Data JPA 的查询方式

You need to run build with JDK or have tools.jar on the classpath

pom

<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-apt</artifactId>
</dependency>
<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.sun</groupId>
    <artifactId>tools</artifactId>
    <version>1.7</version>
    <scope>system</scope>
    <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
</dependency>

官网和一些其他示例并没有提及tools,但没有这个会报错的,IDE里面就报了。

除了上面的配置还要添加构建插件

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

配置完这些之后 Dao需要多继承一个接口QueryDslPredicateExecutor

package com.school1024.spring.boot.data.jpa.dao;
 
import java.util.List;
import java.util.Map;
 
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.query.Param;
 
import com.school1024.spring.boot.data.jpa.model.BookModel;
import com.school1024.spring.boot.data.jpa.model.type.GenderType;
 
public interface BookDao extends JpaRepository<BookModel, Integer>, JpaSpecificationExecutor<BookModel>,
        QueryDslPredicateExecutor<BookModel> {
 
}

这个接口里的方法可以接收 com.querydsl.core.types.Predicate 类型的参数,注意这个类型是querydsl的,与 javax.persistence.criteria.Predicate 是有区别的。

测试用例

@Test
public void test9() {
    QBookModel qbook = QBookModel.bookModel;
 
    com.querydsl.core.types.Predicate predicate = qbook.gender.eq(GenderType.MALE).and(qbook.name.like("%张三%"));
 
    Iterable<BookModel> rs = dao.findAll(predicate);
 
    for (BookModel bookModel : rs) {
        System.out.println(bookModel);
    }
 
}

输出结果:BookModel [id=1, name=张三疯自传, author=张三, gender=MALE]

测试数据参考:http://www.school1024.com/spring/spring-data-jpa-query-example.html

更多Querydsl用法参考:http://www.querydsl.com/

原文  http://www.school1024.com/spring/spring-data-jpa-via-query-dsl-querydata.html
正文到此结束
Loading...