SpringBoot SpringDataJPA 动态查询、多条件查询
Spring-data - JPA用的还是比较多的,之前在公司也一直在用,因为方便。下面我们来整理一下如何配置。
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>springdatajpademo</groupId>
<artifactId>springdatajpademo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<!-- base setting -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.locales>zh_CN</project.build.locales>
<project.build.jdk>1.7</project.build.jdk>
<java.version>1.7</java.version>
<!-- lib versions -->
<org.springframework.version>4.1.9.RELEASE</org.springframework.version>
<org.springframework.data.version>1.9.2.RELEASE</org.springframework.data.version>
<!-- <org.hibernate.version>4.3.7.Final</org.hibernate.version> -->
<org.hibernate.version>5.1.1.Final</org.hibernate.version>
<mysql.connector.version>5.1.32</mysql.connector.version>
<hessian.version>4.0.7</hessian.version>
<fastjson.version>1.2.7</fastjson.version>
<org.eclipse.jetty.version>9.1.0.v20131115</org.eclipse.jetty.version>
<org.apache.cxf.version>2.7.7</org.apache.cxf.version>
<project.name>data-manager-server</project.name>
<main.class>com.goldmsg.res.Bootstrap</main.class>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- spring data jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${org.springframework.data.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.15</version>
</dependency>
</dependencies>
</project>
userInfo.java
import javax.persistence.*;
/**
* Created with IntelliJ IDEA.
* User: lu
* Date: 17-3-30
* Time: 下午5:57
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name="obj_user")
@NamedQuery(name="UserInfo.findAll", query="SELECT o FROM UserInfo o")
public class UserInfo {
private int userId;
private String name;
private int age;
private long high;
@javax.persistence.Id
@Column(name="user_id")
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getHigh() {
return high;
}
public void setHigh(long high) {
this.high = high;
}
}
UserInfoDao.java
public interface UserInfoDao extends PagingAndSortingRepository<UserInfo, String>, JpaSpecificationExecutor<UserInfo> {
}
UserInfoSpecDao.java
import com.springdatajpademo.pojo.UserInfo;
import com.springdatajpademo.pojo.UserInfo_;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
/**
* Created with IntelliJ IDEA.
* User: lu
* Date: 17-3-30
* Time: 下午8:05
* To change this template use File | Settings | File Templates.
*/
public class UserInfoDaoSpec {
public static Specification<UserInfo> getSpec(final String name,final int age,final int high) {
return new Specification<UserInfo>() {
@Override
public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate p1 = null;
if(name!=null) {
Predicate p2 = cb.equal(root.get(UserInfo_.name),name);
if(p1 != null) {
p1 = cb.and(p1,p2);
} else {
p1 = p2;
}
}
if(age!=0) {
Predicate p2 = cb.equal(root.get(UserInfo_.age), age);
if(p1 != null) {
p1 = cb.and(p1,p2);
} else {
p1 = p2;
}
}
if(high!=0) {
Predicate p2 = cb.equal(root.get(UserInfo_.high), high);
if(p1 != null) {
p1 = cb.and(p1,p2);
} else {
p1 = p2;
}
}
return p1;
}
};
}
}
UserInfoExtendDao.java
import com.springdatajpademo.pojo.UserInfo;
import com.springdatajpademo.pojo.UserInfo_;
import com.springdatajpademo.pojo.UserStat;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: lu
* Date: 17-3-31
* Time: 上午10:32
* To change this template use File | Settings | File Templates.
*/
@Repository
public class UserInfoExtendDao {
@PersistenceContext(unitName = "springJpa")
EntityManager em;
public List<UserInfo> getUserInfo(String name,int age,int high) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UserInfo> query = cb.createQuery(UserInfo.class);
//from
Root<UserInfo> root = query.from(UserInfo.class);
//where
Predicate p1 = null;
if(name!=null) {
Predicate p2 = cb.equal(root.get(UserInfo_.name),name);
if(p1 != null) {
p1 = cb.and(p1,p2);
} else {
p1 = p2;
}
}
if(age!=0) {
Predicate p2 = cb.equal(root.get(UserInfo_.age), age);
if(p1 != null) {
p1 = cb.and(p1,p2);
} else {
p1 = p2;
}
}
if(high!=0) {
Predicate p2 = cb.equal(root.get(UserInfo_.high), high);
if(p1 != null) {
p1 = cb.and(p1,p2);
} else {
p1 = p2;
}
}
query.where(p1);
List<UserInfo> userInfos = em.createQuery(query).getResultList();
return userInfos;
}
public UserStat getUserStat(String name) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> query = cb.createTupleQuery();
//from
Root<UserInfo> root = query.from(UserInfo.class);
//select
Selection<Long> countUser;
Selection<Long> sumHigh;
countUser = cb.count(root.get(UserInfo_.userId));
sumHigh = cb.sum(root.get(UserInfo_.high));
CompoundSelection<Tuple> selection = cb.tuple(countUser, sumHigh);
//where
Predicate predicate = cb.equal(root.get(UserInfo_.name), name);
//query
CriteriaQuery<Tuple> criteriaQuery = query.select(selection).where(predicate);
Tuple tuple = em.createQuery(criteriaQuery).getSingleResult();
UserStat userStat = new UserStat();
userStat.setCountUser(tuple.get(countUser));
userStat.setSumHigh(tuple.get(sumHigh));
return userStat;
}
}
Application.java
import com.springdatajpademo.pojo.UserInfo;
import com.springdatajpademo.pojo.UserStat;
import com.springdatajpademo.repository.UserInfoDao;
import com.springdatajpademo.repository.UserInfoDaoSpec;
import com.springdatajpademo.repository.UserInfoExtendDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class Application {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Application application = new Application ();
application .testJpa1(applicationContext);
application .testJpa2(applicationContext);
}
public void testJpa1(ClassPathXmlApplicationContext applicationContext) {
UserInfoExtendDao userInfoExtendDao = (UserInfoExtendDao)applicationContext.getBean("userInfoExtendDao");
List<UserInfo> userInfos = userInfoExtendDao.getUserInfo("张三",16,165);
printUserInfo(userInfos);
UserStat userStat = userInfoExtendDao.getUserStat("张三");
System.out.println(userStat.getCountUser());
System.out.println(userStat.getSumHigh());
}
public void testJpa2(ClassPathXmlApplicationContext applicationContext) {
UserInfoDao userInfoDao = (UserInfoDao)applicationContext.getBean("userInfoDao");
{
//三个条件:"张三",16,165
System.out.println("\n三个条件:张三,16,165");
List<UserInfo> userInfos = userInfoDao.findAll(UserInfoDaoSpec.getSpec("张三",16,165));
printUserInfo(userInfos);
}
{
//两个条件:"张三",16,这里假设赋值0为未赋值
System.out.println("\n两个条件:张三,16");
List<UserInfo> userInfos = userInfoDao.findAll(UserInfoDaoSpec.getSpec("张三",16,0));
printUserInfo(userInfos);
}
{
//两个条件:"张三",16,这里假设赋值0为未赋值
System.out.println("\n一个条件:张三");
List<UserInfo> userInfos = userInfoDao.findAll(UserInfoDaoSpec.getSpec("张三",0,0));
printUserInfo(userInfos);
}
}
private void printUserInfo(List<UserInfo> userInfos) {
if(userInfos!=null) {
for(UserInfo userInfo : userInfos) {
System.out.println("userId:"+userInfo.getUserId()+" name:"+userInfo.getName());
}
}
}
}
以上配置来自网络,有问题可以在下面评论,技术问题可以私聊我。
QQ技术交流群:213365178
SpringBoot SpringDataJPA 动态查询、多条件查询的更多相关文章
- Mybatis中动态SQL多条件查询
Mybatis中动态SQL多条件查询 mybatis中用于实现动态SQL的元素有: if:用if实现条件的选择,用于定义where的字句的条件. choose(when otherwise)相当于Ja ...
- [转]NHibernate之旅(4):探索查询之条件查询(Criteria Query)
本节内容 NHibernate中的查询方法 条件查询(Criteria Query) 1.创建ICriteria实例 2.结果集限制 3.结果集排序 4.一些说明 根据示例查询(Query By Ex ...
- 项目一:第四天 1、快递员的条件分页查询-noSession,条件查询 2、快递员删除(逻辑删除) 3、基于Apache POI实现批量导入区域数据 a)Jquery OCUpload上传文件插件使用 b)Apache POI读取excel文件数据
1. 快递员的条件分页查询-noSession,条件查询 2. 快递员删除(逻辑删除) 3. 基于Apache POI实现批量导入区域数据 a) Jquery OCUpload上传文件插件使用 b) ...
- MySQL数据库6 -查询基础,简单查询,条件查询,对查询结果排序
一.SELECT语句 SELECT COL1,COL2,....COLn FROM TABLE1,TABLE2,....TABLEn [WHERE CONDITIONS] -- 查询条件 [GROUP ...
- dhtmlxGrid分页查询,条件查询实例
使用jquery的ajax get将页面条件请求到后台,取得数据库数据,分页查询,返回前台grid中. 引入所需文件: <script>window.dhx_globalImgPath = ...
- MySQL数据库—查询基础,简单查询,条件查询,对查询结果排序
一.SELECT语句 SELECT COL1,COL2,....COLn FROM TABLE1,TABLE2,....TABLEn [WHERE CONDITIONS] -- 查询条件 [GROUP ...
- Mybatis框架模糊查询+多条件查询
一.ISmbmsUserDao层 //根据姓名模糊查询 public List<Smbms> getUser(); //多条件查询 public List<Smbms> get ...
- 软件测试最常用的 SQL 命令 | 掌握基本查询、条件查询、聚合查询
1.DML核心CRUD增删改查 缩写全称和对应 SQL: * DML 数据操纵语言:Data Manipulation Language * Create 增加:insert * Retrieve 查 ...
- MySQL——基础查询与条件查询
基础查询 /* 语法: select 查询列表 from 表名; 类似于:System.out.println(打印东西); 1.查询列表可以是:表中的字段.常量值.表达式.函数 2.查询的结果是一个 ...
随机推荐
- 初遇Java
什么是JVM?JVM是java虚拟机(JVM Java Virtual Machine),java程序需要运行在虚拟机上,不同平台有自己的虚拟机,因此java语言可以跨平台. 什么是JRE?包括Jav ...
- Sturts2中Action的搜索顺序
http://localhost:8080/ProjectName/path1/path2/path3/XX.action 首先会判断以/path1/paht2/path3为namespace的pac ...
- HDU 5178 pairs(双指针)
HDU 5178 pairs(双指针) Hdu 5178 解法:因为要求的是绝对值小于等于k,因此数字的序号关系并不重要,那么排序后使用双指针即可解决这个问题. #include<queue&g ...
- Python基础(九) 内置模块
今天学习Python中的模块,模块类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才能完成(函 ...
- nginx 4 win10
去下载文件 http://nginx.org/en/download.html 然后释放文件到一目录 最后执行nginx.exe.到浏览器查看localhost,界面: 在最后,别忘了,修改其80端口 ...
- NOIP2005 树网的核
题目描述 Description [问题描述]设 T=(V, E, W) 是一个无圈且连通的无向图(也称为无根树),每条边带有正整数的权,我们称T 为树网(treenetwork),其中V, E分别表 ...
- 夜话JAVA设计模式之策略模式
策略模式 定义了算法簇,分别封装起来,让他们之间可以互相替换,让算法簇的变化独立于使用算法的客户.设计原则1 找出应用中可能需要变化之处,把他们独立出来,不要和那些不需要变化的代码混在 ...
- 基本的文件I/O
基本的文件 I/O 抽象基类 Stream 支持读取和写入字节. Stream 集成了异步支持. 其默认实现根据其相应的异步方法来定义同步读取和写入,反之亦然. 所有表示流的类都是从 Stream 类 ...
- PHP array_pad()
定义和用法 array_pad() 函数向一个数组插入带有指定值的指定数量的元素. 语法 array_pad(array,size,value) 参数 描述 array 必需.规定数组. size 必 ...
- .net core2.0添加json文件并转化成类注入控制器使用 让js调试更简单—console
.net core2.0添加json文件并转化成类注入控制器使用 上一篇,我们介绍了如何读取自定义的json文件,数据是读取出来了,只是处理的时候太麻烦,需要一遍一遍写,很枯燥.那么有没有很好的办法呢 ...