SpringDataJPA+QueryDSL玩转态动条件/投影查询

  在本文之前,本应当专门有一篇博客讲解SpringDataJPA使用自带的Specification+JpaSpecificationExecutor去说明如何玩条件查询,但是看到新奇、编码更简单易懂的技术总是会让人感到惊喜,而且QueryDSL对SpringDataJPA有着完美的支持。如果你没有使用过自带的Specification去做复杂查询,不用担心,本节分享的QueryDSL技术与SpringDataJPA自带支持的Specification没有关联。注意,本文内容一切都是基于SpringBoot1.x上构建的,如果还没有使用过SpringBoot的伙伴,请移步SpringBoot进行初步入门。

 

1、QueryDSL简介

  如果说Hibernate等ORM是JPA的实现,而SpringDataJPA是对JPA使用的封装,那么QueryDSL可以是与SpringDataJPA有着同阶层的级别,它也是基于各种ORM之上的一个通用查询框架,使用它的API类库可以写出“Java代码的sql”,不用去手动接触sql语句,表达含义却如sql般准确。更重要的一点,它能够构建类型安全的查询,这比起JPA使用原生查询时有很大的不同,我们可以不必再对恶心的“Object[]”进行操作了。当然,我们可以SpringDataJPA + QueryDSL JPA联合使用,它们之间有着完美的相互支持,以达到更高效的编码。

2、QueryDSL JPA的使用

2.1 编写配置

2.1.1 pom.xml配置

在maven pom.xml的plugins标签中配置以下plugin:

    <build>
        <plugins>
            <!--其他plugin...........-->

            <!--因为是类型安全的,所以还需要加上Maven APT plugin,使用 APT 自动生成一些类:-->
            <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</outputDirectory>
                            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

继续在pom.xml 的dependencies中配置以下依赖:

<dependencies>
        <!--SpringDataJPA-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!--Web支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--QueryDSL支持-->
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <scope>provided</scope>
        </dependency>
        <!--QueryDSL支持-->
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

2.1.2 application.properties配置

application.properties与之前几篇SpringDataJPA文章的application.yml配置作用是相同的,配置如下:

server.port=8888
server.context-path=/
server.tomcat.uri-encoding=utf-8

#数据源配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot_test?characterEncoding=utf8
#数据库账号
spring.datasource.username=root
#数据库密码
spring.datasource.password=
spring.jpa.database=mysql
#是否展示sql
spring.jpa.show-sql=true
#是否自动生/更新成表,根据什么策略
spring.jpa.hibernate.ddl-auto=update
#命名策略,会将Java代码中的驼峰命名法映射到数据库中会变成下划线法
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy

2.1.3 JPAQueryFactory配置

使用QueryDSL的功能时,会依赖使用到JPAQueryFactory,而JPAQueryFactory在这里依赖使用EntityManager,所以在主类中做如下配置,使得Spring自动帮我们注入EntityManager与自动管理JPAQueryFactory:

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
    //让Spring管理JPAQueryFactory
    @Bean
    public JPAQueryFactory jpaQueryFactory(EntityManager entityManager){
        return new JPAQueryFactory(entityManager);
    }
}

2.1.4 编写实体建模

在这里我们先介绍单表,待会儿介绍多表时我们在进行关联Entity的配置

@Data
@Entity
@Table(name = "t_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer userId;
    private String username;
    private String password;
    private String nickName;
    private Date birthday;
    private BigDecimal uIndex;  //排序号
}

这个实体类非常简单,相信大家一定有所理解。没有使用过@Data注解,也可以不用,暂且就将他当做可以自动生成getXXX/setXXX方法的工具,如果你没有使用这个注解,也可以直接使用IDEA快捷键进行生成setXXX/getXXX。如果想了解这类注解,请前往lombok介绍

2.1.5 执行maven命令

然后在IDEA中选中你的MavenProject按钮,选中你的maven项目,双击compile按钮:

如果你的控制台提示你compile执行失败了,那么请留意一下你的maven路径是否在IDEA中进行了正确的配置。

以上步骤执行完毕后,会在你的target中自动生成了QUser类:

该类中的代码大致是这样的:

@Generated("com.querydsl.codegen.EntitySerializer")
public class QUser extends EntityPathBase<User> {

    private static final long serialVersionUID = -646136422L;

    public static final QUser user = new QUser("user");

    public final DateTimePath<java.util.Date> birthday = createDateTime("birthday", java.util.Date.class);

    public final StringPath nickName = createString("nickName");

    public final StringPath password = createString("password");

    public final NumberPath<java.math.BigDecimal> uIndex = createNumber("uIndex", java.math.BigDecimal.class);

    public final Numbe
  • 43
    点赞
  • 188
    收藏
    觉得还不错? 一键收藏
  • 20
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值