SpringBoot环境下QueryDSL-JPA的使用

1、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-×××tance"
         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.xiaohang.springio</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

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

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--<scope>runtime</scope>-->
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
        <!-- querydsl -->
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <plug×××>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.5.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>
            <!-- 自动生成query type查询实体 -->
            <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>
        </plug×××>
    </build>
</project>

2、application.yml配置文件

# 数据库基本配置
spring.datasource.type: com.alibaba.druid.pool.DruidDataSource
spring.datasource.username: root
spring.datasource.password: root
spring.datasource.url: jdbc:mysql://192.168.56.1:3306/test01?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.driver-class-name: com.mysql.jdbc.Driver
# 数据库方言
spring.jpa.properties.hibernate.dialect: org.hibernate.dialect.MySQL57Dialect
spring.jpa.show-sql: true
spring.jpa.hibernate.ddl-auto: update
# 数据库平台
spring.jpa.database-platform: mysql
# JPA配置
spring.jpa.database: mysql
# 禁用视图
spring.jpa.open-in-view: false

3、实体类

Customer.java

package com.xiaohang.springio.jpastudy.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "t_customer")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "customer_name")
    private String name;
    @Column(name = "customer_part")
    private String part;
}

Employees.java

package com.xiaohang.springio.jpastudy.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "t_employee")
public class Employees {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "employee_name")
    private String name;
    @Column(name = "employee_part")
    private String part;
}

4、Repository

package com.xiaohang.springio.jpastudy.repository;

import com.xiaohang.springio.jpastudy.entity.Employees;
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeesRepository extends JpaRepository<Employees, Long> {
}
package com.xiaohang.springio.jpastudy.repository;

import com.xiaohang.springio.jpastudy.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

5、JPAQueryFactory类的使用重点

package com.xiaohang.springio.jpastudy.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xiaohang.springio.jpastudy.entity.Customer;
import com.xiaohang.springio.jpastudy.entity.Employees;
import com.xiaohang.springio.jpastudy.entity.QCustomer;
import com.xiaohang.springio.jpastudy.entity.QEmployees;
import com.xiaohang.springio.jpastudy.repository.CustomerRepository;
import com.xiaohang.springio.jpastudy.repository.EmployeesRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;

import javax.persistence.EntityManager;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class BookServiceTest {
    // 注入JPAQueryFactory
    @Bean
    @Autowired
    public JPAQueryFactory jpaQuery(EntityManager entityManager) {
        return new JPAQueryFactory(entityManager);
    }

    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private EmployeesRepository employeesRepository;
    @Autowired
    private CustomerRepository customerRepository;

    @org.junit.Test
    public void jpaQuery() {
        Employees employees = new Employees();
        employees.setName("老李");
        employees.setPart("运营部");
        employeesRepository.saveAndFlush(employees);
    }

    @org.junit.Test
    public void updateBook() {
        Customer customer = new Customer();
        customer.setName("老黄");
        customer.setPart("生产部");
        customerRepository.saveAndFlush(customer);
    }

    /**
     * 数据库联接查询
     */
    @org.junit.Test
    public void findAllAuthors() {
        QCustomer qc = QCustomer.customer;
        QEmployees qe = QEmployees.employees;
        // 内联接
        List<Employees> employeesList = jpaQueryFactory.select(Projections.constructor(Employees.class, qe.id, qe.name, qe.part)).from(qe).innerJoin(qc).on(qc.id.eq(qe.id)).fetch();
        employeesList.forEach(e -> {
            System.out.println(e.getName());
        });
        // 左联接
        List<Employees> employeesList1 = jpaQueryFactory.select(Projections.constructor(Employees.class, qe.id, qe.name, qe.part)).from(qe).leftJoin(qc).on(qc.id.eq(qe.id)).fetch();
        employeesList1.forEach(employees -> {
            System.out.println(employees.getName());
        });
        // 右联接
        List<Employees> employeesList2 = jpaQueryFactory.select(Projections.constructor(Employees.class, qe.id, qe.name, qe.part)).from(qe).rightJoin(qc).on(qc.id.eq(qe.id)).fetch();
        employeesList2.forEach(employees -> {
            System.out.println(employees.getName());
        });
        // 左外
        List<Employees> employeesList3 = jpaQueryFactory.select(Projections.constructor(Employees.class, qe.id, qe.name, qe.part)).from(qe).leftJoin(qc).on(qc.id.eq(qe.id)).where(qc.id.isNull()).fetch();
        employeesList3.forEach(employees -> {
            System.out.println(employees.getName());
        });

    }

    /**
     * 多条件查询
     */
    @org.junit.Test
    public void findAll() {
        // select customer0_.id as id1_1_, customer0_.customer_name as customer2_1_, customer0_.customer_part as customer3_1_ from t_customer customer0_ where (customer0_.customer_name like ? escape ‘!‘ or customer0_.customer_name=?) and (customer0_.id between ? and ?)
        QCustomer qc = QCustomer.customer;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qc.name.like(‘%‘ + "刘" + ‘%‘));
        builder.or(qc.name.eq("老王"));
        builder.and(qc.id.between(3, 5));
        List<Customer> customerList = jpaQueryFactory.selectFrom(qc).where(builder).fetch();
        customerList.forEach(customer -> {
            System.out.println(customer.getName());
        });
    }

    /**
     * 子查询
     */
    @org.junit.Test
    public void findAllDto() {
        QCustomer qc = QCustomer.customer;
        QEmployees qe = QEmployees.employees;
        List<Customer> customerList = jpaQueryFactory.selectFrom(qc).where(qc.id.eq(JPAExpressions.select(qe.id).from(qe).where(qe.name.eq("老张")))).fetch();
        customerList.forEach(customer -> {
            System.out.println(customer.getName());
        });
    }

    /**
     * 排序
     */
    @Test
    public void testDesc() {
        QCustomer qc = QCustomer.customer;
        List<Customer> customerList = jpaQueryFactory.selectFrom(qc).orderBy(qc.id.desc()).fetch();
        customerList.forEach(customer -> {
            System.out.println(customer.getName());
        });
    }

    /**
     * 分页
     */
    @Test
    public void testPage() {
        QCustomer qc = QCustomer.customer;
        QEmployees qe = QEmployees.employees;
        // 写法一
        JPAQuery<Employees> employeesJPAQuery = jpaQueryFactory.selectFrom(qe);
        // offset 起始页
        List<Employees> employeesList = employeesJPAQuery.offset(3).limit(2).fetch();
        employeesList.forEach(employees -> {
            System.out.println(employees);
        });
        // 写法二
        Long total = employeesJPAQuery.fetchCount();
        QueryResults<Customer> customerQueryResults = jpaQueryFactory.selectFrom(qc).offset(0).limit(3).fetchResults();
        List<Customer> results = customerQueryResults.getResults();
        results.forEach(customer -> {
            System.out.println(results);
        });
    }
}

6、推存阅读及参考

https://www.jianshu.com/p/69dcb1b85bbb

原文地址:https://blog.51cto.com/12012821/2409553

时间: 2024-11-09 02:37:21

SpringBoot环境下QueryDSL-JPA的使用的相关文章

springboot环境下配置过滤器和拦截器

以前我们在配置过滤器和拦截器的时候,都是一个类继承一个接口,然后在xml中配置一下就ok 但是,但是,这是springboot的环境,没有xml的配置.所以我们还要继续学习啊啊啊啊啊~~~~~ 先简单大致说明一下,过滤器我们可以直接在类上加上@Component注解实现,但是有些参数啥的还是不好配置,还是需要一个配置文件来搞,所以,spring给我们提供了一个注解,就相当于xml,然后每个方法返回一个对象用@Bean来标注,相当于<bean></bean>注解   看代码吧 Tim

在springboot环境下tk-mybatis的使用记录

1. 新建springboot工程 访问https://start.spring.io/,新建一个springboot工程. 自动生成的工程主要的注意点如下: 1)pom.xml <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.2.RELEASE&l

【技术】JavaSE环境下JPA实体类自动注册

在没有容器支持的环境下,JPA的实体类(Entity)一般要在persistence.xml中逐个注册,类似下面这样: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w

springboot多环境下配置文件

最近研究了一下springboot下不同环境(测试环境.生产环境)下不同配置文件的加载方式,本文是通过修改pom文件中的参数进行配置,具体方法如下: 1.首先要建立三个配置文件:application.yml.application-dev.yml.application-prop.yml,在dev以及prop中进行真正的环境配置,在application.yml中仅仅需要输入如下语句即可: 2.在pom文件中添加如下配置: 3.此时就完成了多环境下的配置,在需要切换环境的时候仅仅需要修改pom

[评测]低配环境下,PostgresQL和Mysql读写性能简单对比

[评测]低配环境下,PostgresQL和Mysql读写性能简单对比 原文链接:https://www.cnblogs.com/blog5277/p/10658426.html 原文作者:博客园--曲高终和寡 *******************如果你看到这一行,说明爬虫在本人还没有发布完成的时候就抓走了我的文章,导致内容不完整,请去上述的原文链接查看原文**************** 由于最近经过朋友启发,又有了一个写个人项目的小想法,在这次个人项目中准备学习并使用一些之前自己没有掌握的新

SpringCloud从入门到进阶(四)——生产环境下Eureka的完全分布式部署

内容 由于前两节的内容我们知道,开启了preferIpAddress后,Eureka的伪分布式部署会提示replica不可用.这一节我们讲解如何在生产环境下部署完全分布式的Eureka集群,确保开启了preferIpAddress后replica的可用性. 版本 IDE:IDEA 2017.2.2 x64 JDK:1.8.0_171 manve:3.3.3 SpringBoot:1.5.9.RELEASE SpringCloud:Dalston.SR1 适合人群 Java开发人员 节点信息: 节

Nacos(五):多环境下如何“读取”Nacos中相应的配置

前言 前景回顾: Nacos(四):SpringCloud项目中接入Nacos作为配置中心 Nacos(三):Nacos与OpenFeign的对接使用 Nacos(二):SpringCloud项目中接入Nacos作为注册中心 通过前面几篇介绍,已经基本了解了Nacos做为注册中心和配置中心的基本用法. 在实际开发中,通常一个系统会准备开发环境.测试环境.预发环境.正式环境 那么如何保证指定环境启动时服务能正确读取到Nacos上相应环境的配置文件呢 本文主要对Nacos作为配置中心时,如何对多环境

定制windows环境下cmd替代软件ConEmu

定制windows环境下cmd替代软件ConEmu 公认的是Windows环境下命令行界面太难用. 不管是cmd还是powershell都不顺手!!窗口宽度不能全屏,字体太难看还不能调整,窗口背景不能更换,永远的黑白配,最痛苦的是复制和粘贴.都不知道MS是怎么想的?搞个这么个反人类的东西出来,还万年不变,从Windows诞生到Windows7不论是桌面版还是服务器版都一样,到了windows8/windows10换成powershell一样的鸡肋. 在百度搜了一下,找到cmd的替代软件conem

《高可用MySQL》1 – Windows环境下压缩版MySQL安装

近日在读O'REILIY系列的<高可用MySQL>, 自然少不了主从(Master-Slave)配置和横向扩展相关的内容. Master-Slave这东西吧.在很多公司都是标配.开发中基本天天都用.遇到的问题自然也不少(如主从不同步,Master宕机).但操作权限很有限.有些东西,仅仅有自己看了.做了,才干真正知道原理是什么,也才干更好的去把握. 本文是高可用MySQL的第一篇读书笔记,主要记录Windows环境下压缩版MySQL(基于安装版的傻瓜式安装过程这里不再提及)的安装过程. 1. 从