2018-03-16

聊聊JPA Criteria查询中的坑

JPA Criteria查询被称作动态安全类型查询,比JPQL这种方式更加健壮。关于JPA Criteria查询在IBM社区有一篇很好的文章,这里我就不去Copy(尊重默默为社区奉献的同行兄弟),请移步https://www.ibm.com/developerworks/cn/java/j-typesafejpa/

Bug复现

场景

创建一个Student类,然后创建其StaticMetaModel Student_类;然后使用Critirial查询年龄大于20的Student。场景很简单,但是。。。结果很意外,让我们来看看相关配置和代码。

配置

依赖配置

<?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.kylin</groupId>
    <artifactId>jpa-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jpa-demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8
        </project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

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

</project>

yml配置文件

server:
  port: 8800
spring:
  datasource:
    password: 123456
    username: root
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jpaadvance
  jpa:
    database-platform: mysql
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect
        

代码

Student类代码

package com.kylin.jpademo.domain;

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table
public class Student implements Serializable {
    private static final long serialVersionUID = -7681363673194194734L;

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(updatable = false, nullable = false)
    private String id;
    private String name;
    private int age;

    //geter and seter

Student_类代码

package com.kylin.jpademo.domain;

import com.kylin.jpademo.domain.metamodel.Student;//重点看这里

import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;

@StaticMetamodel(Student.class)
public class Student_ {
    public static volatile SingularAttribute<Student, String> id;
    public static volatile SingularAttribute<Student, String> name;
    public static volatile SingularAttribute<Student, Integer> age;
}

Repository接口

package com.kylin.jpademo.repository;

import com.kylin.jpademo.domain.metamodel.Student;

import java.util.List;

public interface StudentRepository {
    List<Student> findStudentByAgeLessThan(int age);
}

Repository实现

package com.kylin.jpademo.repository.impl;

import com.kylin.jpademo.domain.metamodel.Student;
import com.kylin.jpademo.domain.Student_;
import com.kylin.jpademo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import java.util.List;

@Transactional
@Repository
public class StudentRepositoryImpl implements StudentRepository {
    @Autowired
    EntityManager em;

    @Override
    public List<Student> findStudentByAgeLessThan(int age) {
        System.out.println(age);
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Student> cq = cb.createQuery(Student.class);

        Root<Student> s = cq.from(Student.class); // from ...
        Path<Integer> path = s.get(Student_.age);
        Predicate condition = cb.gt(path, age);  // condition: attribute > age
        cq.where(condition); // where

        TypedQuery<Student> tq = em.createQuery(cq);
        return tq.getResultList();
    }
}

执行findStudentByAgeLessThan方法

bug复现

如上图所示,报了一个NullPointerException,定位到了StudentRepositoryImpl类的这一行

Path<Integer> path = s.get(Student_.age);

尝试解决

Debug重新运行之后,发现Student_.age变量为空,说明StaticMetaModelStudent_类并没有映射到Student类。之后我google了很多方法去解决这个问题,都没有用。但是可以确定的是一定是StaticMetaModel出了问题,因为将上面出错那一行的代码改为"age"之后,即:

Path<Integer> path = s.get(“age”);

Bug解决了,但这似乎违背了Criteria查询的宗旨,就是类型安全和避免运行时错误,这里的安全类型除了指明确查询中的类型安全之外,还有就是避免使用常量。如果"age"字符串手抖写成了“aeg”,在编译时肯定是没有问题的,只有在运行时才会暴露出来,到了那个时候为时已晚。所以为了尽可能的遵循Criteria的初衷,这种方式肯定不是很好的方案,之后笔者又尝试了很多种方案,都宣告失败。于是我删掉了Student_类重新写了一次,但是这次StudentStudent_位于同一包中,神奇的事情发生了,这次运行正确,并且成功查找出了年龄大于20的Student。

此时的工程结构

修改后的工程结构

结果如下:

[
    {
        "id": "8a4ffa05622dcf1501622dd0aaa30003",
        "name": "bob",
        "age": 90
    },
    {
        "id": "8a4ffa05622dcf1501622dd0ca410004",
        "name": "an",
        "age": 30
    }
]

结论

StudentStudent_必须位于同一包中。

更好的解决办法

解决之后,本人始终百思不得其解,google了很多文章也没有解决。在之后的各种尝试中,发现了自动生成StaticMetaModelStudent_的方法,就是引入下面的依赖。

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-jpamodelgen</artifactId>
        <version>1.1.1.Final</version>
</dependency>

此依赖可以自动创建metamodel。
现在我们删除我们自行创建的Student_类,然后引入上述依赖,保持问题语句:

Path<Integer> path = s.get(Student_.age);

此时程序会出现编译错误:

编译出错

因为刚才删除了Student_类,肯定会出现编译问题。
抛开编译问题,这里我们继续执行,如下图所示,执行成功了。
执行成功

那么为什么呢?总结刚才的操作,你可能会猜测是不是刚才引入的依赖自动创建了Student_呢?答案是肯定的。为了证实这一点,我们去看编译运行的结果:
image.png

自动生成的Student_代码:

package com.kylin.jpademo.domain;

import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;

@StaticMetamodel(Student.class)
public abstract class Student_ {

    public static volatile SingularAttribute<Student, String> name;
    public static volatile SingularAttribute<Student, String> id;
    public static volatile SingularAttribute<Student, Integer> age;

}

执行查询,没有问题。
可以看出自动生成的Student_Student在同一包下,这也印证了刚才的做法。

结论

在Criteria查询中,Model和StaticMetaModel必须位于同一包下。因为在大型项目中,会涉及到很多Model,若不想自己创建对应的StaticMetaModel,可以使用hibernate-jpamodelgen依赖,自动创建。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • 泛型:泛型优点: 1,编译时可以保证类型安全。 2,不用做类型转换,获得一定的性能提升。 泛型约束: where ...
    hui_free阅读 198评论 0 2
  • 1、Doctype作用?标准模式与兼容模式各有什么区别? 1、声明位于位于HTML文档中的第一行,处于 标签之前...
    CRUD_科科阅读 447评论 0 6
  • 破旧的老电梯 伫立在A座补习大楼里 老人拉着小孩 或是大孩子独自上课 我敢打赌 都不喜欢这破旧的老电梯 他实在是太...
    讼儿阅读 263评论 5 15
  • 画家是画画的人,文学家是写作的人,天地万物,世间诸技,回归本质是相通的,绘画和文学虽为艺术的不同载体,但他们都是为...
    方阳普阅读 493评论 21 7
  • 想说的话太多,却不知从何说起,大概因为职业的关系,所以对于医患这块相对关注比较大,近期从魏的死到陈主任的被砍,...
    榆之木阅读 438评论 0 0