目录
SpringDataJpa,jpa,hibernate之间的关系
2.编写SpringDataJPA的配置文件(applicationContext.xml)
JpaSpecificationExecutor封装好的方法
一、SpringDataJPa
介绍springDataJPa
Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!
Spring Data JPA 是更大的 Spring Data 系列的一部分,可以轻松实现基于 JPA 的存储库。该模块处理对基于 JPA 的数据访问层的增强支持。它使构建使用数据访问技术的 Spring 驱动的应用程序变得更加容易。
SpringDataJPA其实是对JPA规范的封装抽象,底层还是使用了Hibernate的JPA技术实现,引用JPQL(Java Persistence Query Language)查询语言,属于Spring整个生态体系的一部分。随着Spring Boot和Spring Cloud在市场上的流行,Spring Data JPA也逐渐进入大家的视野,它们组成有机的整体,使用起来比较方便,加快了开发的效率,使开发者不需要关心和配置更多的东西,完全可以沉浸在Spring的完整生态标准实现下。JPA上手简单,开发效率高,对对象的支持比较好,又有很大的灵活性,市场的认可度越来越高。
官网地址:Spring Data JPA
SpringDataJpa,jpa,hibernate之间的关系
底层工作的还是Hibernate,听说啊,JPA与Hibernate的创始人是同一人。

二、搭建环境
1.创建Maven工程,导入坐标
JPA
com.dynamic
1.0.0-SNAPSHOT
4.0.0
JPA-Day2
5.0.2.RELEASE
5.0.7.Final
1.6.6
1.2.12
0.9.1.2
5.1.6
junit
junit
4.12
test
org.aspectj
aspectjweaver
1.6.8
org.springframework
spring-aop
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-orm
${spring.version}
org.springframework
spring-beans
${spring.version}
org.springframework
spring-core
${spring.version}
org.hibernate
hibernate-core
${hibernate.version}
org.hibernate
hibernate-entitymanager
${hibernate.version}
org.hibernate
hibernate-validator
5.2.1.Final
c3p0
c3p0
${c3p0.version}
log4j
log4j
${log4j.version}
org.slf4j
slf4j-api
${slf4j.version}
org.slf4j
slf4j-log4j12
${slf4j.version}
mysql
mysql-connector-java
${mysql.version}
org.springframework.data
spring-data-jpa
1.9.0.RELEASE
org.springframework
spring-test
${spring.version}
javax.el
javax.el-api
2.2.4
org.glassfish.web
javax.el
2.2.4
2.编写SpringDataJPA的配置文件(applicationContext.xml)
3.创建实体类,数据库表
package com.dynamic.domain; import javax.persistence.*; / * @Author: Promsing(张有博) * @Date: 2021/10/13 - 17:29 * @Description: 客户的实体类 * 配置映射关系 * 1.实体类和表的映射关系 * @Entity 声明是实体类 * @Table(name = "cst_customer") 实体类与表的映射关系,name配置表的名称 * * 2.实体类中属性和表字段的映射关系 * @version: 1.0 */ @Entity @Table(name = "cst_customer") public class Customer { / * @Id:声明主键的配置 * @GeneratedValue:配置主键的生成策略 * strategy * GenerationType.IDENTITY :自增,mysql * * 底层数据库必须支持自动增长(底层数据库支持的自动增长方式,对id自增) * GenerationType.SEQUENCE : 序列,oracle * * 底层数据库必须支持序列 * GenerationType.TABLE : jpa提供的一种机制,通过一张数据库表的形式帮助我们完成主键自增 * GenerationType.AUTO : 由程序自动的帮助我们选择主键生成策略 * @Column:配置属性和字段的映射关系 * name:数据库表中字段的名称 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "cust_id") private Long id;//主键 @Column(name="cust_name") private String custName; @Column(name="cust_source") private String custSource; @Column(name = "cust_industry") private String custIndustry;//所属行业 @Column(name="cust_level") private String custLevel; @Column(name = "cust_address") private String custAddress; @Column(name = "cost_phone") private String custPhone; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public String getCustSource() { return custSource; } public void setCustSource(String custSource) { this.custSource = custSource; } public String getCustIndustry() { return custIndustry; } public void setCustIndustry(String custIndustry) { this.custIndustry = custIndustry; } public String getCustLevel() { return custLevel; } public void setCustLevel(String custLevel) { this.custLevel = custLevel; } public String getCustAddress() { return custAddress; } public void setCustAddress(String custAddress) { this.custAddress = custAddress; } public String getCustPhone() { return custPhone; } public void setCustPhone(String custPhone) { this.custPhone = custPhone; } @Override public String toString() { return "Customer{" + "id=" + id + ", custName='" + custName + '\'' + ", custSource='" + custSource + '\'' + ", custIndustry='" + custIndustry + '\'' + ", custLevel='" + custLevel + '\'' + ", custAddress='" + custAddress + '\'' + ", custPhone='" + custPhone + '\'' + '}'; } }
4.数据库表的SQL
CREATE TABLE `cst_customer` ( `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)', `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)', `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源', `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业', `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别', `cust_address` varchar(128) DEFAULT NULL COMMENT '客户联系地址', `cust_phone` varchar(64) DEFAULT NULL COMMENT '客户联系电话', `cost_phone` varchar(255) DEFAULT NULL, PRIMARY KEY (`cust_id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
5.DAO接口
package com.dynamic.dao; import com.dynamic.domain.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import java.util.List; / * @Author: Promsing(张有博) * @Date: 2021/10/17 - 17:36 * @Description: 需要符合springDataJPA的dao层接口规范 * JpaRepository
<操作的实体类型,实体类中主键属性的类型>
* *封装了基本的CRUD操作 * JpaSpecificationExecutor
<操作的实体类型>
* *封装了复杂查询(分页) * @version: 1.0 */ public interface CustomerDao extends JpaRepository
, JpaSpecificationExecutor
{ }
操作的实体类型>
操作的实体类型,实体类中主键属性的类型>
三、四种查询方式:
1.基本的增删改查
继承JpaRepository,JpaSpecificationExecutor 接口,使用JPA封装好的方法。
JpaRepository封装好的方法

JpaSpecificationExecutor封装好的方法

测试类
/ * findOne(id) :根据id查询 * * save(customer):保存或更新 实体的id属性 * * delete(id) :根据id删除 * * findAll() :查询全部 * * count() :计数 * * exists() :判断是否存在 * */ @Test public void testFindOne(){ System.out.println("dfa"); Customer one = dao.findOne(1L); System.out.println(one); } @Test public void testSave(){ System.out.println("dfa"); Customer c=new Customer(); c.setCustAddress("廊坊"); c.setCustName("小小张"); c.setCustPhone("9999"); c.setCustLevel("vipp"); Customer save = dao.save(c); System.out.println(save); } @Test @Transactional public void testUpdate(){ System.out.println("dfa"); Customer c=new Customer(); c.setCustAddress("廊坊"); c.setCustName("小小张"); c.setCustPhone("2800"); Customer save = dao.save(c); System.out.println(save); } @Test public void testDelete(){ dao.delete(2L); System.out.println(); } @Test @Transactional public void testFindAll(){ List
all = dao.findAll(); for (Customer customer : all) { System.out.println(customer); } System.out.println(); } @Test @Transactional public void testCount(){ long count = dao.count(); System.out.println(count); } @Test public void testExists(){ boolean exists = dao.exists(2L); System.out.println(exists); } @Test @Transactional public void testGetOne(){ // getOone方法是懒加载 Customer one = dao.getOne(2L); System.out.println(one); }
2.JPQL查询
jpa query language (jpq查询语言),与原生SQL语句类似,并且完全面向对象,通过类名和属性访问,查询的是类和类中的属性
上一篇博客介绍了JPQL:
需要将JPQL语句配置到接口方法上
1.特有的查询:需要在dao接口上配置方法
2.在新添加的方法上,使用注解的形式配置jpql查询语句
3.注解 : @Query
DAO接口:
/ * @Author: Promsing(张有博) * @Date: 2021/10/17 - 17:36 * @Description: 需要符合springDataJPA的dao层接口规范 * JpaRepository
<操作的实体类型,实体类中主键属性的类型>
* *封装了基本的CRUD操作 * JpaSpecificationExecutor
<操作的实体类型>
* *封装了复杂查询(分页) * @version: 1.0 */ public interface CustomerDao extends JpaRepository
, JpaSpecificationExecutor
{ / * @Query:表示查询 * * @Modifying 表示更新的操作 */ @Query(value = "from Customer where custName = ? ") public List
findJpql(String custName); / * 对于多个占位符参数 * 赋值的时候,默认情况下,占位符的位置需要和方法参数中的位置保持一致 * * 可以指定占位符参数的位置 * ? 索引的方式,指定此占位符的取值来源 */ @Query(value = "from Customer where custName = ? and id = ?") // @Query(value = "from Customer where custName = ?2 and id = ?1") public Object findCustNameAndId(String name,Long id); @Query(value = "update Customer set custName = ? where id = ? ") @Modifying //表示是,更新的操作 public Integer updateName(String name,Long id); }
操作的实体类型>
操作的实体类型,实体类中主键属性的类型>
测试类:
@Test public void testJpql(){ List
list = dao.findJpql("小小张"); System.out.println(list); } @Test public void testFindCustNameAndId(){ Object one = dao.findCustNameAndId("小小张",1L); System.out.println(one); } @Test @Transactional //添加事务的支持 @Rollback(value = false) / * springDataJpa中使用jpql完成更新/删除操作 * 需要手动添加事务的支持 * 默认会执行结束之后,回滚事务 * @Rollback: 设置是否自动回滚 * false(不) | true */ public void testUpdateName(){ Object one = dao.updateName("张自由",3L); System.out.println(one); }
3.SQL查询
1.特有的查询:需要在dao接口上配置方法
2.在新添加的方法上,使用注解的形式配置sql查询语句
3.注解 : @Query
value :jpql语句 | sql语句
nativeQuery :false(使用jpql查询) | true(使用本地查询:sql查询)
DAO接口
package com.dynamic.dao; import com.dynamic.domain.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import java.util.List; / * @Author: Promsing(张有博) * @Date: 2021/10/17 - 17:36 * @Description: 需要符合springDataJPA的dao层接口规范 * JpaRepository
<操作的实体类型,实体类中主键属性的类型>
* *封装了基本的CRUD操作 * JpaSpecificationExecutor
<操作的实体类型>
* *封装了复杂查询(分页) * @version: 1.0 */ public interface CustomerDao extends JpaRepository
, JpaSpecificationExecutor
{ / * 使用sql的形式查询 查询全部用户 * SQL:select * from cst_customer * @Query: 配置sql查询 * value:sqly语句 * nativeQuery:查询方式 * true:sql查询 * false:jpql查询 * @return */ @Query(value = "select * from cst_customer", nativeQuery = true) public List
findSql(); @Query(value = "select * from cst_customer where cust_name like ?", nativeQuery = true) public List
findLikeSql(String name ); }
操作的实体类型>
操作的实体类型,实体类中主键属性的类型>
测试类:
@Test public void testSQL(){ List
list = dao.findSql(); List
sql = dao.findLikeSql("小%"); for (Customer customer : sql) { System.out.println(customer); } }
4.方法命名查询
是对jpql查询,更加深入一层的封装
我们只需要按照SpringDataJpa提供的方法名称规则定义方法,不需要再配置jpql语句,完成查询
按照Spring Data JPA 定义的规则,查询方法以findBy开头,涉及条件查询时,条件的属性用条件关键字连接,要注意的是:条件属性首字母需大写。框架在进行方法名解析时,会先把方法名多余的前缀截取掉,然后对剩下部分进行解析。
部分对照表
|
Keyword |
Sample |
JPQL |
||
|
And |
findByLastnameAndFirstname |
… where x.lastname = ?1 and x.firstname = ?2 |
||
|
Or |
findByLastnameOrFirstname |
… where x.lastname = ?1 or x.firstname = ?2 |
||
|
Is,Equals |
findByFirstnameIs, findByFirstnameEquals |
… where x.firstname = ?1 |
||
|
Between |
findByStartDateBetween |
… where x.startDate between ?1 and ?2 |
||
|
LessThan |
findByAgeLessThan |
… where x.age < ?1 |
||
|
LessThanEqual |
findByAgeLessThanEqual |
… where x.age ⇐ ?1 |
||
|
GreaterThan |
findByAgeGreaterThan |
… where x.age > ?1 |
||
|
GreaterThanEqual |
findByAgeGreaterThanEqual |
… where x.age >= ?1 |
||
|
After |
findByStartDateAfter |
… where x.startDate > ?1 |
||
|
Before |
findByStartDateBefore |
… where x.startDate < ?1 |
||
|
IsNull |
findByAgeIsNull |
… where x.age is null |
||
|
IsNotNull,NotNull |
findByAge(Is)NotNull |
… where x.age not null |
||
|
Like |
findByFirstnameLike |
… where x.firstname like ?1 |
||
|
NotLike |
findByFirstnameNotLike |
… where x.firstname not like ?1 |
||
|
StartingWith |
findByFirstnameStartingWith |
… where x.firstname like ?1 (parameter bound with appended %) |
||
|
EndingWith |
findByFirstnameEndingWith |
… where x.firstname like ?1 (parameter bound with prepended %) |
||
|
Containing |
findByFirstnameContaining |
… where x.firstname like ?1 (parameter bound wrapped in %) |
||
|
OrderBy |
findByAgeOrderByLastnameDesc |
… where x.age = ?1 order by x.lastname desc |
||
|
Not |
findByLastnameNot |
… where x.lastname <> ?1 |
||
|
In |
findByAgeIn(Collection ages) |
… where x.age in ?1 |
||
|
NotIn |
findByAgeNotIn(Collection age) |
… where x.age not in ?1 |
||
|
TRUE |
findByActiveTrue() |
… where x.active = true |
||
|
FALSE |
findByActiveFalse() |
… where x.active = false |
||
|
IgnoreCase |
findByFirstnameIgnoreCase |
… where UPPER(x.firstame) = UPPER(?1) |
DAO接口:
package com.dynamic.dao; import com.dynamic.domain.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import java.util.List; / * @Author: Promsing(张有博) * @Date: 2021/10/17 - 17:36 * @Description: 需要符合springDataJPA的dao层接口规范 * JpaRepository
<操作的实体类型,实体类中主键属性的类型>
* *封装了基本的CRUD操作 * JpaSpecificationExecutor
<操作的实体类型>
* *封装了复杂查询(分页) * @version: 1.0 */ public interface CustomerDao extends JpaRepository
, JpaSpecificationExecutor
{ / * 方法名的约定 * * findBy:查询 * 对象中的属性名(首字母大写),查询条件 * * findByCustName 根据客户名称查询 * * 会根据方法名称进行解析 findBy from XXX where custName * @param name * @return */ //1.findBy +属性名称(根据属性名称进行完成匹配的查询=) public Customer findByCustName(String name ); //2.findBy +属性名称 +“查询方式”(Like | isNull) public List
findByCustNameLike(String name ); //3.findBy +属性名称 +“查询方式” +“多条件的连接符(and|or)” +属性名 +“查询方式” public Customer findByCustNameLikeAndCustIndustry(String name,String industry); }
操作的实体类型>
操作的实体类型,实体类中主键属性的类型>
测试类:
@Test public void testFindNaming(){ Customer custName = dao.findByCustName("张自由"); System.out.println(custName); System.out.println("______________"); List
byCustNameLike = dao.findByCustNameLike("小%"); for (Customer customer : byCustNameLike) { System.out.println(customer); } System.out.println("______________"); Customer it = dao.findByCustNameLikeAndCustIndustry("小%", "IT教育"); System.out.println(it); }
如果本篇博客对您有一定的帮助,大家记得留言+点赞+收藏哦。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/210513.html原文链接:https://javaforall.net
