ITPub博客

首页 > 应用开发 > > SpringDataJpa入门案例及查询详细解析(深度好文)

SpringDataJpa入门案例及查询详细解析(深度好文)

作者:coyan 时间:2019-10-10 10:34:28 0 删除 编辑

java互联网高级架构 



1.SpringDataJpa Spring Data JPA

让我们解脱了DA0层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作工程中,推荐使用Spring Data JPA+ORM(如:hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使数据库层操作更加简单,方便解耦。

把JPA规范的代码封装起来,真正进行查询的还是hibernate或mybatis >>(封装了jdbc操作),然后进行查询或操作数据库。

2.SpringDataJpa入门操作(搭建环境)

2.1创建工程,导入坐标

项目所需的依赖坐标

<?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>cn.itcast</groupId>
 <artifactId>jpa-day02</artifactId>
 <version>1.0-SNAPSHOT</version>
 <properties>
 <spring.version>5.0.2.RELEASE</spring.version>
 <hibernate.version>5.0.7.Final</hibernate.version>
 <s1f4j.version>1.6.6</s1f4j.version>
 <log4j.version>1.2.12</log4j.version>
 <c3pe.version>0.9.1.2</c3pe.version>
 <mysql.version>5.1.6</mysql.version>
 </properties>
 <dependencies>
 <!--junit单元测试-->
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.9</version>
 <scope>test</scope>
 </dependency>
 <!--spring beg-->
 <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjweaver</artifactId>
 <version>1.6.8</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-aop</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context-support</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <!--spring对ORm框架的支持包-->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-orm</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-beans</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <!--spring end-->
 <!--hibernate beg-->
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
 <version>${hibernate.version}</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-entitymanager</artifactId>
 <version>${hibernate.version}</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator</artifactId>
 <version>5.2.1.Final</version>
 </dependency>
 <!--hibernate end-->
 <!--c3p0 beg-->
 <dependency>
 <groupId>c3p0</groupId>
 <artifactId>c3p0</artifactId>
 <version>0.9.1.2</version>
 </dependency>
 <!--log end-->
 <dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
 </dependency>
 <dependency>
 <groupId>org.slf4j</groupId>
 <artifactId>slf4j-api</artifactId>
 <version>1.7.25</version>
 </dependency>
 <dependency>
 <groupId>org.slf4j</groupId>
 <artifactId>slf4j-log4j12</artifactId>
 <version>1.6.6</version>
 </dependency>
 <!--log end-->
 <dependency>
 <groupId>mysq1</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.6</version>
 </dependency>
 <!-- spring data jpa 的坐标 -->
 <dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-jpa</artifactId>
 <version>1.9.0.RELEASE</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-test</artifactId>
 <version>4.2.4.RELEASE</version>
 </dependency>
 <!--el beg 使用spring data jpa必须引入-->
 <dependency>
 <groupId>javax.el</groupId>
 <artifactId>javax.el-api</artifactId>
 <version>2.2.4</version>
 </dependency>
 <dependency>
 <groupId>org.glassfish.web</groupId>
 <artifactId>javax.el</artifactId>
 <version>2.2.4</version>
 </dependency>
 <dependency>
 <groupId>org.projectlombok</groupId>
 <artifactId>lombok</artifactId>
 <version>1.16.22</version>
 </dependency>
 </dependencies>
</project>


配置Spring的配置文件

<!--创建entityManagerFactory对象交给Spring容器管理-->
 <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> (权限定位类名)
 <property name="dataSource" ref="dataSource"/> (依赖注入)
 <property name="packagesToScan " value="cn.itcast.domain"/> (配置的扫描的包,实体类所在的包)
 <property name="persistenceProvider"> (JPA的实现厂家)
 <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
 </property>
 <!--jpa的供应商适配器-->
 <property name="jpaVendorAdapter">
 <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
 <!--配置是否自动创建数据库表-->
 <property name="generateDdl" value="false"/>
 <!--指定数据库类型-->
 <property name="database" value="MYSQL"/>
 <!--数据库方言:支持的特有语法(不同数据库有不同的语法)-->
 <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
 <!--是否显示sql-->
 <property name="showSql" value="true"/>
 </bean>
 </property>
 <!--jpa的方言 :高级特性(配置了谁就拥有了谁的高级特性)-->
 <property name="jpaDialect">
 <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"></bean>
 </property>
 </bean>
 <!--2.创建数据库连接池-->
 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 <property name="user" value="root"></property>
 <property name="password" value="123456"></property>
 <property name="jdbcUrl" value="jdbc:mysq1:///jpa"></property>
 <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
 </bean>
(以下的不需要特别记忆)>>>
 <!--3.整合spring dataJpa-->
 <jpa:repositories base-package="cn.itcast.dao" transaction-manager-ref="transactionManager"
 entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
 <!--4.配置事务管理器-->
 <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
 <property name="entityManagerFactory" ref="entityManagerFactory"></property>
 </bean>
 <!--5.声明式事务-->
 <!--6.配置 包扫描-->
 <context:component-scan base-package="cn.itcast"></context:component-scan>
</beans>


编写符合SpringDataJpa规范额dao层接口

package cn.itcast.dao;
import cn.itcast.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
 * 符合springDataJpa的dao层接口规范
 * JpaRepository<操作的实体类类型,实体类中主键属性的类型) >>>封装了基本的CRUD操作
 * JpaSpecificationExecutor<操作的实体类类型> >>>封装了复杂查询()
 */
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {}


完成客户的增删改查操作

根据id查询

findOne

em.find() 立即加载

getOne

@Transactional:保证getOne正常运行

em.getReference() 延迟加载 >>返回的是一个客户的动态代理对象,什么时候用、什么时候查询

@Test

public void testFindOne() {

Customer customer = customerDao.findOne(3l);

System.out.println(customer);

}

保存和更新(sava)

如果没有id主键属性:>> 保存

@Test

public void testSave() {

Customer customer = new Customer();

customer.setCustname("黑马程序员");

customer.setCustaddress("北京");

customer.setCustindustry("IT教育");

customerDao.save(customer);

}

存在id主键属性: >> 根据id查询数据,更新数据

@Test

public void testUpdate() {

Customer customer = new Customer();

customer.setCustid(1l);

customer.setCustname("播客");

customer.setCustindustry("黑马程序员很厉害");

customerDao.save(customer);

}

根据id删除(delete)

@Test

public void testDelete() {

Customer customer = new Customer();

customerDao.delete(1l);

}

查询所有客户(findAll)

@Test

public void findAll(){

List list = customerDao.findAll();

for (Customer customer : list) {

System.out.println(customer);

}

SpringDataJpa的运行过程和原理剖析

1. 通过JdkDynamicAopProxy的 invoke 方法创建了一个动态代理对象

2. simpleJpaRepository当中封装了 JPA的操作(借助JPA的api完成数据库的CRUD)

3. 通过 hibernate完成数据库操作(封装了jdbc)

复杂查询

借助接口中的定义好的方法完成查询

findone(id):根据id查询

测试统计查询:查询客户的总数量

@Test

public void testdount() {

long count = customerDao.count();//查询全部的客户数量System.out.println(count);

System.out.println(count);

}

测试:判断id为3的客户是否存在

可以查询以下id为3的客户

如果值为空,代表不存在,如果不为空,代表存在

判断数据库中id为3的客户的数量

如果数量为0,代表不存在(false),如果大于0,代表存在(true)

@Test

public void testExists() {

boolean exists = customerDao.exists(3l);

System.out.println(exists);

}

jpql的查询方式♦♦

jpql:jpa query language( jpq查询语言 )

特点:语法或关键字和sql语句类似

查询的是类和类中的属性

需要将JPQL语句配置到接口方法上

1 .特有的查询:需要在dao接口上配置方法

2. 在新添加的方法上,使用注解的形式配置jpql查询语句

3. 注解:@Query

案例:根据客户名称查询名称 >> 使用Jpql的形式查询

CustomerDao

public interface CustomerDao extends JpaRepository, JpaSpecificationExecutor {

/**

* 案例:根据客户名称查询名称

* 使用Jpql的形式查询

* jpql: from Customer where custName = ?

*/

@Query(value = "from Customer where custname = ?")

public Customer findJpql(String custname);

}

JpqlTest

@Test

public void testFindJpql(){

Customer customer = customerDao.findJpql("传智");

System.out.println(customer);

}

案例:根据客户名称和客户id查询客户 >> 使用Jpql的形式查询

对于多个占位符参数: 赋值的时候,默认的情况下,占位符的位置需要和方法参数中的位置保持一致 [ custName >> String name custId >> Long id ]

@Query(value="from Customer where custName=? and custId=?")

public Customer findCustNameAndId (String name , Long id );

也可以指定占位符参数的位置 : ?索引的方式,指定此占位的取值来源

@Query (value=" from Customer where custName = ?2 and custId = ?1 ")

public Customer findCustNameAndId ( Long id , String name );

CustomerDao

@Query(value = "from Customer where custname = ? and custid = ?")

public Customer findCustNameAndId(String custname, long id);

JpqlTest

@Test

public void testCustNameAndId(){

Customer customer = customerDao.findCustNameAndId("黑马",2l);

System.out.println(customer);

}

使用jpql完成更新操作案例:根据id更新更新2号客户的名称,将名称改为“黑马程序员”

CustomerDao

@Query(value = " update Customer set custname = ?2 where custid = ?1 ") //代表的是进行查询

@Modifying //当前执行的是一个更新操作

//更新不需要返回值 选择void

public void UpdateCustomer( long custid,String custname);

JpqlTest  

@Test

@Transactional //添加对事务的支持

@Rollback(value = false) //设置是否自动回滚

public void testUpdateCustomer(){

customerDao.UpdateCustomer(2l,"黑马程序员");

}

执行结束后,默认回滚事务,可以通过@Rollback 设置是否自动回滚 >> false | true

SQL查询方式.

1 .特有的查询:需要在dao接口上配置方法

2. 在新添加的方法上,使用注解的形式配置sql查询语句

3. 注解:@Query

value: jsql | sql

nativeQuery : fals(使用jpql查询) l true(使用本地查询:sql查询)

CustomerDao

@Query(value = "select * from cst_customer",nativeQuery = true)

public ListfindSql();

JpqlTest 

@Test

public void testfindSql(){

List list = customerDao.findSql();

for (Object[] obj : list) {

System.out.println(Arrays.toString(obj));//每一个里面都还是object数组,所以需要借助Arrays.toString()方法打印数组

}

方法命名规则查询

>> 1: findBy +属性名(首字母大写)

public Customer findByCustname(String custname);

@Test

public void testNaming(){

Customer customer = customerDao.findByCustname("传智");

System.out.println(customer);

}

>> 2: findBy + 属性名(首字母大写)+ “查询方式”

public List findByCustnameLike(String custname);

@Test

public void testfindByCustnameLike(){

List list = customerDao.findByCustnameLike("黑马%");

for (Customer customer : list) {

System.out.println(customer);

} }

>> 3: findBy + 属性名(首字母大写)+ “查询方式” + “多条件的连接符(and | or)” + 属性名 + “查询方式”

 使用客户名称模糊匹配和客户所属行业精准匹配的查询

public List findByCustnameLikeAndCustindustry(String custname, String custindustry); //结果可能是一个或多个,所以选择List

Specifications动态查询

root :查询的根对象(查询的任何属性都可以从根对象中获取)

cirteriaQuery:顶层查询对象,自定义查询方式(了解,一般不用)

cirteriaBuilder:查询的构造器,封装了很多查询条件

public Predicate toPredicate(Root root , CriteriaQuery query , CriteriaBuilder cb) { } //封装查询条件

查询客户名为 “传智” 的客户

@Test

public void testSpec() {

实现Specification接口( 提供泛型 :查询的对象属性)

Specification spec = new Specification() {

实现toPredicate方法(构造查询条件)

public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {

//1.获取比较的属性

Path

//2.构造查询条件

Predicate predicate = cb.equal(custname, "传智"); //进行精准的匹配(custname:比较的属性 , “传智”:比较的属性取值)

return predicate;

}};

Customer customer = customerDao.findOne(spec);

System.out.println(customer);

}

查询客户名为 “黑马2” 并且行业为 "it教育" 的的客户

@Test

public void testSpec1() {

Specification spec = new Specification() {

public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {

//1.获取比较的属性

Path

Path

//2.构造查询条件

Predicate p1 = cb.equal(custname, "黑马2");

Predicate p2 = cb.equal(custindustry, "it教育");

and(与关系):满足条件1并且满足条件2 or(或关系):满足条件1或满足条件2

Predicate and = cb.and(p1, p2);

return and;

}

};

Customer customer = customerDao.findOne(spec);

System.out.println(customer);

}

案例:完成根据客户名称的模糊匹配,返回客户列表 >>客户名称以 “传智播客” 开头

默认: equal:直接得到 path对象(属性),然后进行比较即可

gt(大于),lt(小于),ge(大于等于),le(小于等于),like:得到path对象,根据path指定比较的参数类型,再去进行比较

指定参数类型:path.as(类型的字节码对象)

@Test

public void testSpec2() {

Specification spec = new Specification() {

public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {

Path

Predicate predicate = cb.like(custname.as(String.class), "传智播客%"); //查询方式:模糊匹配

return predicate;

}

};

List list = customerDao.findAll(spec);

for (Customer customer : list) {

System.out.println(customer);

} }

添加排序 >>创建排序对象,需要调用构造方法实例化sort对象

第一个参数:排序的顺序(倒序,正序)

Sort.Direction.DESC:倒序

Sort.Direction.ASC:升序

第二个参数:排序的属性名称

Sort sort = new Sort(Sort.Direction.DESC, "custid");

List list = customerDao.findAll(spec, sort);

分页查询

不带参数的分页查询

创建PageRequest的过程中,需要调用他的构造方法传入两个参数

第一个参数:当前查询的页数(从e开始)

第二个参数:每页查询的数量

@Test

public void testSpec3() {

Specification spec = null; //不带参数

Pageable pageable = new PageRequest(0, 2);

//分页查询

Page page = customerDao.findAll(null, pageable);

System.out.println(page.getContent());//得到数据集合列表

System.out.println(page.getTotalElements());//得到总条数

System.out.println(page.getTotalPages());//得到总页数

}

带参数分页查询

@Test

public void testSpec4() {

Specification spec = new Specification() {

public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {

Path custname = root.get("custname");

Predicate predicate = criteriaBuilder.equal(custname, "传智播客");

return predicate;

}};

Pageable pageable = new PageRequest(0, 2);

//分页查询

Page page = customerDao.findAll(spec, pageable);

System.out.println(page.getContent());//得到数据集合列表

System.out.println(page.getTotalElements());//得到总条数

System.out.println(page.getTotalPages());//得到总页数

custname = root.get("custname"); //查询属性:客户名

custindustry = root.get("custindustry");

custname = root.get("custname");

完成客户的增删改查操作

根据id查询

findOne

em.find() 立即加载

getOne

@Transactional:保证getOne正常运行

em.getReference() 延迟加载 >>返回的是一个客户的动态代理对象,什么时候用、什么时候查询

@Test

public void testFindOne() {

Customer customer = customerDao.findOne(3l);

System.out.println(customer);

}

保存和更新(sava)

如果没有id主键属性:>> 保存

@Test

public void testSave() {

Customer customer = new Customer();

customer.setCustname("黑马程序员");

customer.setCustaddress("北京");

customer.setCustindustry("IT教育");

customerDao.save(customer);

}

存在id主键属性: >> 根据id查询数据,更新数据

@Test

public void testUpdate() {

Customer customer = new Customer();

customer.setCustid(1l);

customer.setCustname("播客");

customer.setCustindustry("黑马程序员很厉害");

customerDao.save(customer);

}

根据id删除(delete)

@Test

public void testDelete() {

Customer customer = new Customer();

customerDao.delete(1l);

}

查询所有客户(findAll)

@Test

public void findAll(){

List list = customerDao.findAll();

for (Customer customer : list) {

System.out.println(customer);

}

SpringDataJpa的运行过程和原理剖析

1. 通过JdkDynamicAopProxy的 invoke 方法创建了一个动态代理对象

2. simpleJpaRepository当中封装了 JPA的操作(借助JPA的api完成数据库的CRUD)

3. 通过 hibernate完成数据库操作(封装了jdbc)

复杂查询

借助接口中的定义好的方法完成查询

findone(id):根据id查询

测试统计查询:查询客户的总数量

@Test

public void testdount() {

long count = customerDao.count();//查询全部的客户数量System.out.println(count);

System.out.println(count);

}

测试:判断id为3的客户是否存在

可以查询以下id为3的客户

如果值为空,代表不存在,如果不为空,代表存在

判断数据库中id为3的客户的数量

如果数量为0,代表不存在(false),如果大于0,代表存在(true)

@Test

public void testExists() {

boolean exists = customerDao.exists(3l);

System.out.println(exists);

}

jpql的查询方式♦♦

jpql:jpa query language( jpq查询语言 )

特点:语法或关键字和sql语句类似

查询的是类和类中的属性

需要将JPQL语句配置到接口方法上

1 .特有的查询:需要在dao接口上配置方法

2. 在新添加的方法上,使用注解的形式配置jpql查询语句

3. 注解:@Query

案例:根据客户名称查询名称 >> 使用Jpql的形式查询

CustomerDao

public interface CustomerDao extends JpaRepository, JpaSpecificationExecutor {

/**

* 案例:根据客户名称查询名称

* 使用Jpql的形式查询

* jpql: from Customer where custName = ?

*/

@Query(value = "from Customer where custname = ?")

public Customer findJpql(String custname);

}

JpqlTest

@Test

public void testFindJpql(){

Customer customer = customerDao.findJpql("传智");

System.out.println(customer);

}

案例:根据客户名称和客户id查询客户 >> 使用Jpql的形式查询

对于多个占位符参数: 赋值的时候,默认的情况下,占位符的位置需要和方法参数中的位置保持一致 [ custName >> String name custId >> Long id ]

@Query(value="from Customer where custName=? and custId=?")

public Customer findCustNameAndId (String name , Long id );

也可以指定占位符参数的位置 : ?索引的方式,指定此占位的取值来源

@Query (value=" from Customer where custName = ?2 and custId = ?1 ")

public Customer findCustNameAndId ( Long id , String name );

CustomerDao

@Query(value = "from Customer where custname = ? and custid = ?")

public Customer findCustNameAndId(String custname, long id);

JpqlTest

@Test

public void testCustNameAndId(){

Customer customer = customerDao.findCustNameAndId("黑马",2l);

System.out.println(customer);

}

使用jpql完成更新操作案例:根据id更新更新2号客户的名称,将名称改为“黑马程序员”

CustomerDao

@Query(value = " update Customer set custname = ?2 where custid = ?1 ") //代表的是进行查询

@Modifying //当前执行的是一个更新操作

//更新不需要返回值 选择void

public void UpdateCustomer( long custid,String custname);

JpqlTest  

@Test

@Transactional //添加对事务的支持

@Rollback(value = false) //设置是否自动回滚

public void testUpdateCustomer(){

customerDao.UpdateCustomer(2l,"黑马程序员");

}

执行结束后,默认回滚事务,可以通过@Rollback 设置是否自动回滚 >> false | true

SQL查询方式.

1 .特有的查询:需要在dao接口上配置方法

2. 在新添加的方法上,使用注解的形式配置sql查询语句

3. 注解:@Query

value: jsql | sql

nativeQuery : fals(使用jpql查询) l true(使用本地查询:sql查询)

CustomerDao

@Query(value = "select * from cst_customer",nativeQuery = true)

public ListfindSql();

JpqlTest 

@Test

public void testfindSql(){

List list = customerDao.findSql();

for (Object[] obj : list) {

System.out.println(Arrays.toString(obj));//每一个里面都还是object数组,所以需要借助Arrays.toString()方法打印数组

}

方法命名规则查询

>> 1: findBy +属性名(首字母大写)

public Customer findByCustname(String custname);

@Test

public void testNaming(){

Customer customer = customerDao.findByCustname("传智");

System.out.println(customer);

}

>> 2: findBy + 属性名(首字母大写)+ “查询方式”

public List findByCustnameLike(String custname);

@Test

public void testfindByCustnameLike(){

List list = customerDao.findByCustnameLike("黑马%");

for (Customer customer : list) {

System.out.println(customer);

} }

>> 3: findBy + 属性名(首字母大写)+ “查询方式” + “多条件的连接符(and | or)” + 属性名 + “查询方式”

 使用客户名称模糊匹配和客户所属行业精准匹配的查询

public List findByCustnameLikeAndCustindustry(String custname, String custindustry); //结果可能是一个或多个,所以选择List

Specifications动态查询

root :查询的根对象(查询的任何属性都可以从根对象中获取)

cirteriaQuery:顶层查询对象,自定义查询方式(了解,一般不用)

cirteriaBuilder:查询的构造器,封装了很多查询条件

public Predicate toPredicate(Root root , CriteriaQuery query , CriteriaBuilder cb) { } //封装查询条件

查询客户名为 “传智” 的客户

@Test

public void testSpec() {

实现Specification接口( 提供泛型 :查询的对象属性)

Specification spec = new Specification() {

实现toPredicate方法(构造查询条件)

public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {

//1.获取比较的属性

Path

//2.构造查询条件

Predicate predicate = cb.equal(custname, "传智"); //进行精准的匹配(custname:比较的属性 , “传智”:比较的属性取值)

return predicate;

}};

Customer customer = customerDao.findOne(spec);

System.out.println(customer);

}

查询客户名为 “黑马2” 并且行业为 "it教育" 的的客户

@Test

public void testSpec1() {

Specification spec = new Specification() {

public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {

//1.获取比较的属性

Path

Path

//2.构造查询条件

Predicate p1 = cb.equal(custname, "黑马2");

Predicate p2 = cb.equal(custindustry, "it教育");

and(与关系):满足条件1并且满足条件2 or(或关系):满足条件1或满足条件2

Predicate and = cb.and(p1, p2);

return and;

}

};

Customer customer = customerDao.findOne(spec);

System.out.println(customer);

}

案例:完成根据客户名称的模糊匹配,返回客户列表 >>客户名称以 “传智播客” 开头

默认: equal:直接得到 path对象(属性),然后进行比较即可

gt(大于),lt(小于),ge(大于等于),le(小于等于),like:得到path对象,根据path指定比较的参数类型,再去进行比较

指定参数类型:path.as(类型的字节码对象)

@Test

public void testSpec2() {

Specification spec = new Specification() {

public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {

Path

Predicate predicate = cb.like(custname.as(String.class), "传智播客%"); //查询方式:模糊匹配

return predicate;

}

};

List list = customerDao.findAll(spec);

for (Customer customer : list) {

System.out.println(customer);

} }

添加排序 >>创建排序对象,需要调用构造方法实例化sort对象

第一个参数:排序的顺序(倒序,正序)

Sort.Direction.DESC:倒序

Sort.Direction.ASC:升序

第二个参数:排序的属性名称

Sort sort = new Sort(Sort.Direction.DESC, "custid");

List list = customerDao.findAll(spec, sort);

分页查询

不带参数的分页查询

创建PageRequest的过程中,需要调用他的构造方法传入两个参数

第一个参数:当前查询的页数(从e开始)

第二个参数:每页查询的数量

@Test

public void testSpec3() {

Specification spec = null; //不带参数

Pageable pageable = new PageRequest(0, 2);

//分页查询

Page page = customerDao.findAll(null, pageable);

System.out.println(page.getContent());//得到数据集合列表

System.out.println(page.getTotalElements());//得到总条数

System.out.println(page.getTotalPages());//得到总页数

}

带参数分页查询

@Test

public void testSpec4() {

Specification spec = new Specification() {

public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {

Path custname = root.get("custname");

Predicate predicate = criteriaBuilder.equal(custname, "传智播客");

return predicate;

}};

Pageable pageable = new PageRequest(0, 2);

//分页查询

Page page = customerDao.findAll(spec, pageable);

System.out.println(page.getContent());//得到数据集合列表

System.out.println(page.getTotalElements());//得到总条数

System.out.println(page.getTotalPages());//得到总页数

custname = root.get("custname"); //查询属性:客户名

custindustry = root.get("custindustry");

custname = root.get("custname");

custname = root.get("custname");

custname = root.get("custname");

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2236/viewspace-3159731/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-11

  • 博文量
    271
  • 访问量
    16167