Spring Boot Querydsl 教程

Spring Boot Querydsl 教程展示了如何使用 Querydsl 在 Spring Boot 应用中创建数据库查询。

Querydsl

Querydsl 是一个框架,可通过其流畅的 API 来构造静态类型的类似 SQL 的查询。 Spring Data 模块通过QuerydslPredicateExecutor与 Querydsl 集成。

Spring Querydsl 示例

以下应用使用实体管理器和存储库使用 Querydsl 创建查询。

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           │   MyRunner.java
│   │           ├───model
│   │           │       City.java
│   │           └───repository
│   │                   CityRepository.java
│   └───resources
│           application.properties
│           data-h2.sql
│           schema-h2.sql
└───test
    └───java

这是项目结构。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>springbootquerydsl</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <version>4.2.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>4.2.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!--Plugin for query-dsl-->
            <plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.1.3</version>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <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>

</project>

Maven POM 文件包含 Spring Data JPA,H2 数据库和 Querydsl 的依赖项。 JPAAnnotationProcessor查找带有Entity注解的域类型,并为其生成查询类型。

注解处理是 javac 中的一种工具,用于在编译时扫描和处理注解。

resources/application.properties

spring.main.banner-mode=off
spring.datasource.platform=h2
spring.jpa.hibernate.ddl-auto=none
logging.pattern.console=%d{dd-MM-yyyy HH:mm:ss} %magenta([%thread]) %highlight(%-5level) %logger.%M - %msg%n

application.properties是主要的 Spring Boot 配置文件。 使用spring.main.banner-mode属性,我们可以关闭 Spring 标语。 spring.datasource.platform设置数据库的供应商名称。 在初始化脚本中使用它。 最后,spring.jpa.hibernate.ddl-auto禁止从实体自动创建模式。 logging.pattern.console定义控制台的日志模式。

resources/schema-h2.sql

CREATE TABLE cities(id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255), population INT);

启动应用时,将执行schema-h2.sql脚本。 它创建一个新的数据库表。

resources/data-h2.sql

INSERT INTO cities(name, population) VALUES('Bratislava', 432000);
INSERT INTO cities(name, population) VALUES('Budapest', 1759000);
INSERT INTO cities(name, population) VALUES('Prague', 1280000);
INSERT INTO cities(name, population) VALUES('Warsaw', 1748000);
INSERT INTO cities(name, population) VALUES('Los Angeles', 3971000);
INSERT INTO cities(name, population) VALUES('New York', 8550000);
INSERT INTO cities(name, population) VALUES('Edinburgh', 464000);
INSERT INTO cities(name, population) VALUES('Suzhou', 4327066);
INSERT INTO cities(name, population) VALUES('Zhengzhou', 4122087);
INSERT INTO cities(name, population) VALUES('Berlin', 3671000);
INSERT INTO cities(name, population) VALUES('Brest', 139163);
INSERT INTO cities(name, population) VALUES('Bucharest', 1836000);

之后,执行data-h2.sql文件。 它用数据填充表。

com/zetcode/model/City.java

package com.zetcode.model;

import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "cities")
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private int population;

    public City() {
    }

    public City(String name, int population) {
        this.name = name;
        this.population = population;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 79 * hash + Objects.hashCode(this.id);
        hash = 79 * hash + Objects.hashCode(this.name);
        hash = 79 * hash + this.population;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final City other = (City) obj;
        if (this.population != other.population) {
            return false;
        }
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        return Objects.equals(this.id, other.id);
    }

    @Override
    public String toString() {

        var builder = new StringBuilder();
        builder.append("City{id=").append(id).append(", name=")
                .append(name).append(", population=")
                .append(population).append("}");

        return builder.toString();
    }
}

这是City实体。

com/zetcode/repository/CityRepository.java

package com.zetcode.repository;

import com.zetcode.model.City;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CityRepository extends CrudRepository<City, Long>,
        QuerydslPredicateExecutor<City> {

}

要在我们的存储库中启用 Querydsl,我们从QuerydslPredicateExecutor扩展。

com/zetcode/MyRunner.java

package com.zetcode;

import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQuery;
import com.zetcode.model.QCity;
import com.zetcode.repository.CityRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Component
@SuppressWarnings({ "rawtypes", "unchecked" })
public class MyRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(MyRunner.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private CityRepository cityRepository;

    @Override
    public void run(String... args) throws Exception {

        var qCity = QCity.city;

        var query = new JPAQuery(entityManager);

        query.from(qCity).where(qCity.name.eq("Bratislava")).distinct();
        var c1 = query.fetch();

        logger.info("{}", c1);

        var query2 = new JPAQuery(entityManager);
        query2.from(qCity).where(qCity.name.endsWith("est").and(qCity.population.lt(1800000)));
        var cities = query2.fetch();

        logger.info("{}", cities);

        BooleanExpression booleanExpression = qCity.population.goe(2_000_000);
        OrderSpecifier<String> orderSpecifier = qCity.name.asc();
        var cities2 = cityRepository.findAll(booleanExpression, orderSpecifier);

        logger.info("{}", cities2);
    }
}

我们使用EntityManagerCityRepository创建 Querydsl 查询。

var qCity = QCity.city;

Querydsl 创建一个QCity类型。

var query = new JPAQuery(entityManager);

在前两个查询中,我们使用实体管理器。

query.from(qCity).where(qCity.name.eq("Bratislava")).distinct();
var c1 = query.fetch();

logger.info("{}", c1);

使用 Querydsl 的流畅 API,我们获取了一个独特的城市对象。

var query2 = new JPAQuery(entityManager);
query2.from(qCity).where(qCity.name.endsWith("est").and(qCity.population.lt(1800000)));
var cities = query2.fetch();

logger.info("{}", cities);

一个更复杂的查询将获取多个城市。

BooleanExpression booleanExpression = qCity.population.goe(2_000_000);
OrderSpecifier<String> orderSpecifier = qCity.name.asc();
var cities2 = cityRepository.findAll(booleanExpression, orderSpecifier);

logger.info("{}", cities2);

在第三个查询中,我们利用存储库。

Note: In Java enterprise applications it is a good practice to define a service layer that works with repositories. For simplicity reasons, we skip the service layer.

com/zetcode/Application.java

package com.zetcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Application设置 Spring Boot 应用。 @SpringBootApplication启用自动配置和组件扫描。

$ mvn spring-boot:run
...
04-06-2019 13:22:13 [main] INFO  com.zetcode.MyRunner.run - [City{id=1, name=Bratislava, population=432000}]
04-06-2019 13:22:13 [main] INFO  com.zetcode.MyRunner.run - [City{id=2, name=Budapest, population=1759000}, 
City{id=11, name=Brest, population=139163}]
04-06-2019 13:22:13 [main] INFO  com.zetcode.MyRunner.run - [City{id=10, name=Berlin, population=3671000}, 
City{id=5, name=Los Angeles, population=3971000}, City{id=6, name=New York, population=8550000}, 
City{id=8, name=Suzhou, population=4327066}, City{id=9, name=Zhengzhou, population=4122087}]
...

我们运行该应用。

在本教程中,我们展示了如何使用 Querydsl 在 Spring Boot 应用中生成查询。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程