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.查询的结果是一个 ...
随机推荐
- oracle打开或者关闭flashback
1.打开flashback: 关闭数据库 SQL>shutdown immediate; 启动到mount方式 SQL>startup mount; 如果归档没有打开,打开归档[因为fla ...
- 【10】AngularJS SQL
AngularJS SQL 使用 PHP 从 MySQL 中获取数据 <div ng-app="myApp" ng-controller="customersCtr ...
- UVA 12697 Minimal Subarray Length
Minimal Subarray Length Time Limit: 3000ms Memory Limit: 131072KB This problem will be judged on UVA ...
- HDU——1576 A/B
A/B Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submis ...
- Mutual Training for Wannafly Union #5
A(UVA12336) 题意:给一个n*m(n,m<=1e5)的棋盘,棋盘上有一些障碍点不能放棋子,现在要在棋盘上放4个棋子,满足A->B->C->D->A,其中走的规则 ...
- ubuntu 16.04网卡找不到eth0
自15版本开始就不叫eth0.可以通过ifconfig进行查看: ifconfig -a 其中enp3s0才是网卡的名称,lo为环路. 参考: http://blog.csdn.net/christn ...
- Eclipse代码/目录虚线对齐设置
前提: 我的Eclipse版本如下: 比这个版本新或者旧都可以实现如下效果. 实现步骤: 在代码上显示虚线设置有如下方法: 1.如果不使用插件,Eclipse是不支持虚线的,只能是横条的点状,效果如下 ...
- 好纠结啊,JEECG 商业版本号和开源版本号有什么差别呢?
好纠结啊.JEECG 商业版本号和开源版本号有什么差别呢? 2014-12-18 jeecg JEECG tp=webp" style="width: 698px;" a ...
- j2se回想
执行Java程序. Java程序有两种方式一种是jar包.一种是class. 执行jar,Java -jar XXX.jar执行的时候,Java.exe调用GetMainClassName函数,该函数 ...
- LINKs: Xamarin.Forms + Prism
LINK 1 - How to use Prism with Xamarin.Forms http://brianlagunas.com/first-look-at-the-prism-for-xam ...