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 动态查询、多条件查询的更多相关文章

  1. Mybatis中动态SQL多条件查询

    Mybatis中动态SQL多条件查询 mybatis中用于实现动态SQL的元素有: if:用if实现条件的选择,用于定义where的字句的条件. choose(when otherwise)相当于Ja ...

  2. [转]NHibernate之旅(4):探索查询之条件查询(Criteria Query)

    本节内容 NHibernate中的查询方法 条件查询(Criteria Query) 1.创建ICriteria实例 2.结果集限制 3.结果集排序 4.一些说明 根据示例查询(Query By Ex ...

  3. 项目一:第四天 1、快递员的条件分页查询-noSession,条件查询 2、快递员删除(逻辑删除) 3、基于Apache POI实现批量导入区域数据 a)Jquery OCUpload上传文件插件使用 b)Apache POI读取excel文件数据

    1. 快递员的条件分页查询-noSession,条件查询 2. 快递员删除(逻辑删除) 3. 基于Apache POI实现批量导入区域数据 a) Jquery OCUpload上传文件插件使用 b) ...

  4. MySQL数据库6 -查询基础,简单查询,条件查询,对查询结果排序

    一.SELECT语句 SELECT COL1,COL2,....COLn FROM TABLE1,TABLE2,....TABLEn [WHERE CONDITIONS] -- 查询条件 [GROUP ...

  5. dhtmlxGrid分页查询,条件查询实例

    使用jquery的ajax get将页面条件请求到后台,取得数据库数据,分页查询,返回前台grid中. 引入所需文件: <script>window.dhx_globalImgPath = ...

  6. MySQL数据库—查询基础,简单查询,条件查询,对查询结果排序

    一.SELECT语句 SELECT COL1,COL2,....COLn FROM TABLE1,TABLE2,....TABLEn [WHERE CONDITIONS] -- 查询条件 [GROUP ...

  7. Mybatis框架模糊查询+多条件查询

    一.ISmbmsUserDao层 //根据姓名模糊查询 public List<Smbms> getUser(); //多条件查询 public List<Smbms> get ...

  8. 软件测试最常用的 SQL 命令 | 掌握基本查询、条件查询、聚合查询

    1.DML核心CRUD增删改查 缩写全称和对应 SQL: * DML 数据操纵语言:Data Manipulation Language * Create 增加:insert * Retrieve 查 ...

  9. MySQL——基础查询与条件查询

    基础查询 /* 语法: select 查询列表 from 表名; 类似于:System.out.println(打印东西); 1.查询列表可以是:表中的字段.常量值.表达式.函数 2.查询的结果是一个 ...

随机推荐

  1. 每日命令:(9)touch

    linux的touch命令不常用,一般在使用make的时候可能会用到,用来修改文件时间戳,或者新建一个不存在的文件. 1.命令格式: touch [选项]... 文件... 2.命令参数: -a    ...

  2. CCF201409-2 画图 java(100分)

    试题编号: 201409-2 试题名称: 画图 时间限制: 1.0s 内存限制: 256.0MB 问题描述: 问题描述 在一个定义了直角坐标系的纸上,画一个(x1,y1)到(x2,y2)的矩形指将横坐 ...

  3. STM32F103移值FreeRtos笔记

    RTOS版本:FreeRTOS_V8.2.2 一.下载FreeRTOS源文件       这个可以在百度上下载,或者在官网上面下载http://www.freertos.org/a00104.html ...

  4. 洛谷 2048 BZOJ 2006 [NOI2010]超级钢琴

    [题解] 贪心题.设五元组(mx,pos,l,r1,r2)表示最大值为mx,取得最大值的区间右端点为pos,区间左端点为l,区间右端点的可选区间为[r1,r2]. 每次从堆里拎出最大值,然后把这个区间 ...

  5. BZOJ 4415 洛谷 3988 [Shoi2013]发牌

    [题解] 权值线段树.查询当前牌堆顶的牌并且删掉就好了. #include<cstdio> #include<algorithm> #define N 3000010 #def ...

  6. saltstack(三) grains、pillar的使用

    一,grains grains: 这个跟puppet的facter功能一样.主要负责采集客户端一些基本信息, 这个也完全可以自定义,可以在客户端自定义,然后自动汇报上来:也可以从服务器端定义然后推下去 ...

  7. Vue如何tab切换高亮最简易方法

    以往我们实现tab切换高亮通常是循环遍历先把所有的字体颜色改变为默认样式,再点亮当前点击的选项,而我们在vue框架中实现tab切换高亮显示并不需要如此,只需要将当前点击选项的index传入给一个变量, ...

  8. Python学习笔记 (2.1)标准数据类型之Number(数字)

    Python3中,数字分为四种——int,float,bool,complex int(整型) 和数学上的整数表示没啥区别,没有大小限制(多棒啊,不用写整数高精了),可正可负.还可表示16进制,以 0 ...

  9. WEB开发----springboot的登录拦截机制

    如果是一个后台的管理项目的,有些东西是不能直接就可以访问的,必须要登录才可以进去,所以就需要进行登录拦截,只有登录过的用户才可以正常访问. 登录拦截是不会拦截jsp页面的方法,所以我们需要在Contr ...

  10. windows开启3306端口并用可视化工具访问远程mysql(授权访问)

    开启 MySQL 的远程登陆帐号有两大步: 1.确定服务器上的防火墙没有阻止 3306 端口. MySQL 默认的端口是 3306 ,需要确定防火墙没有阻止 3306 端口,否则远程是无法通过 330 ...