@TOC
springDataJpa的概述
Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!
Spring Data JPA 让我们解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作工程中,推荐使用Spring Data JPA + ORM(如:hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使数据库层操作更加简单,方便解耦
springDataJpa的入门操作
案例:客户的基本CRUD
i.搭建环境
创建工程导入坐标
<?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.kt</groupId> <artifactId>springdata_jpa</artifactId> <version>1.0-SNAPSHOT</version> <properties> <spring.version>4.2.4.RELEASE</spring.version> <hibernate.version>5.0.7.Final</hibernate.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <c3p0.version>0.9.1.2</c3p0.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> <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>${c3p0.version}</version> </dependency> <!-- c3p0 end --> <!-- log end --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <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> <!-- el end --> </dependencies> </project>
配置spring的配置文件(applicationContext.xml配置spring Data jpa的整合)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> <!-- 1.dataSource 配置数据库连接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 2.配置entityManagerFactory --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="packagesToScan" value="cn.kt.domain"/> <property name="persistenceProvider"> <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"/> </property> </bean> <!-- 整合spring data jpa--> <jpa:repositories base-package="cn.kt.dao" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"></jpa:repositories> <!-- 3.事务管理器--> <!-- JPA事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <!-- 4.txAdvice--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 5.aop--> <aop:config> <aop:pointcut id="pointcut" expression="execution(* cn.kt.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/> </aop:config> <!--配置包扫描--> <context:component-scan base-package="cn.kt "></context:component-scan> <!--组装其它 配置文件--> </beans>
编写实体类(Customer),使用jpa注解配置映射关系
package cn.kt.domain;/* *Created by tao on 2020-05-04. */ import javax.persistence.*; import java.io.Serializable; @Entity //声明实体类 @Table(name = "cst_customer") //建立实体类和表的映射关系 public class Customer implements Serializable { @Id//声明当前私有属性为主键 @GeneratedValue(strategy = GenerationType.IDENTITY) //配置主键的生成策略 @Column(name = "cust_id") //指定和表中cust_id字段的映射关系 private Long custId; @Column(name = "cust_name") //指定和表中cust_name字段的映射关系 private String custName; @Column(name = "cust_source")//指定和表中cust_source字段的映射关系 private String custSource; @Column(name = "cust_industry")//指定和表中cust_industry字段的映射关系 private String custIndustry; @Column(name = "cust_level")//指定和表中cust_level字段的映射关系 private String custLevel; @Column(name = "cust_address")//指定和表中cust_address字段的映射关系 private String custAddress; @Column(name = "cust_phone")//指定和表中cust_phone字段的映射关系 private String custPhone; public Long getCustId() { return custId; } public void setCustId(Long custId) { this.custId = custId; } 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{" + "custId=" + custId + ", custName='" + custName + '\'' + ", custSource='" + custSource + '\'' + ", custIndustry='" + custIndustry + '\'' + ", custLevel='" + custLevel + '\'' + ", custAddress='" + custAddress + '\'' + ", custPhone='" + custPhone + '\'' + '}'; } }
ii.编写一个符合springDataJpa的dao层接口
- 只需要编写dao层接口,不需要编写dao层接口的实现类
- dao层接口规范
1.需要继承两个接口(JpaRepository,JpaSpecificationExecutor)
2.需要提供响应的泛型
findOne(id) :根据id查询
save(customer):保存或者更新(依据:传递的实体类对象中,是否包含id属性)
delete(id) :根据id删除
findAll() : 查询全部
- CustomerDao.java
package cn.kt.dao;/* *Created by tao on 2020-05-04. */ import cn.kt.domain.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /* * 符合Springdata jpa的dao层接口规范 * JpaRepository<操作的实体类类型>,<实体类中主键属性的类型> * 封住了基本的CRUD操作 * JpaSpecificationExecutor<操作实体类的类型> * 封装了复杂查询的操作(分页) **/ public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> { }
- CustomerTest.java(测试类)
package cn.kt.test;/* *Created by tao on 2020-05-04. */ import cn.kt.dao.CustomerDao; import cn.kt.domain.Customer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) //声明单元测试 @ContextConfiguration(locations = "classpath:applicationContext.xml") public class CustomerTest { @Autowired private CustomerDao customerDao; /* * 查询所有 * */ @Test public void testFindAll() { List<Customer> all = customerDao.findAll(); for (Customer customer : all) { System.out.println(customer); } } /* * 根据id查询 * */ @Test public void testFindOne() { Customer one = customerDao.findOne(3l); System.out.println(one); } /** * 保存客户:调用save(obj)方法 * 对于save方法的解释:如果执行此方法是对象中存在id属性,即为更新操作会先根据id查询,再更新 * 如果执行此方法中对象中不存在id属性,即为保存操作 */ @Test public void testSave() { Customer c = new Customer(); c.setCustName("妮可罗宾"); customerDao.save(c); } @Test public void testUpdate() { /*不会覆盖的修改*/ //根据id查询id为1的客户 Customer customer = customerDao.findOne(10l); //修改客户 customer.setCustIndustry("One Piece"); customer.setCustAddress("海贼王"); //更新 customerDao.save(customer); /*覆盖的修改*/ /*Customer customer = new Customer(); customer.setCustId(10l); customer.setCustIndustry("One Piece"); customerDao.save(customer);*/ } /** * 根据id删除:调用delete(id)方法 */ @Test public void testDelete() { customerDao.delete(9l); } }
springDataJpa的运行过程和原理剖析
1.通过JdkDynamicAopProxy的invoke方法创建了一个动态代理对象
2.SimpleJpaRepository当中封装了JPA的操作(借助JPA的api完成数据库的CRUD)
3.通过hibernate完成数据库操作(封装了jdbc)
复杂查询
i.借助接口中的定义好的方法完成查询
findOne(id):根据id查询,立即加载
getOne(id):根据id查询,延迟加载
testCount():查询客户的总数量
testExists():判断id为4的客户是否存在
<br /> /* *测试统计查询,查询客户的总数量 * */ @Test public void testCount(){ long count = customerDao.count(); System.out.println(count); } /* *测试判断id为4的客户是否存在 * */ @Test public void testExists(){ boolean exists = customerDao.exists(4l); System.out.println("id为4的客户是否存在:"+exists); } /* * findOne() * * 立即加载 * @Transactional 保证getOne正常运行 * getOne() * 延迟加载 * 什么时候用,什么时候加载 * */ @Test @Transactional public void testGetOne(){ Customer one = customerDao.getOne(2l); System.out.println(one); }
ii.jpql的查询方式
jpql : jpa query language (jpq查询语言)
特点:语法或关键字和sql语句类似
查询的是类和类中的属性
需要将JPQL语句配置到接口方法上
1.特有的查询:需要在dao接口上配置方法
2.在新添加的方法上,使用注解的形式配置jpql查询语句
3.注解 : @Query
iii.sql语句的查询
1.特有的查询:需要在dao接口上配置方法
2.在新添加的方法上,使用注解的形式配置sql查询语句
3.注解 : @Query
value :jpql语句 | sql语句
nativeQuery :false(使用jpql查询) | true(使用本地查询:sql查询)
是否使用本地查询
iiii.方法名称规则查询
- 是对jpq1查询,更加深入的一层封装,
- 我们只需要按照SpringDataJpa提供的方法名称规则定义方法,不需要再去配置jpql语句,完成查询
- findBy开头:代表查询
对象中属性的名称(首字母大写)
含义:根据属性名称进行查询
- findBy + 属性名称(根据属性名称进行完成匹配的查询=)
- findBy +属性名称+“查询方式(Like| isnull)
findByCustNameLike - 多条件查询
findBy +属性名+ "查询方式"+ "多条件的连接符(and|or)" +属性名+"查询方式"
复制查询测试
CustomerDao.java(接口)
package cn.kt.dao;/* *Created by tao on 2020-05-04. */ import cn.kt.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; /* * 符合Springdata jpa的dao层接口规范 * JpaRepository<操作的实体类类型>,<实体类中主键属性的类型> * 封住了基本的CRUD操作 * JpaSpecificationExecutor<操作实体类的类型> * 封装了复杂查询的操作(分页) **/ public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> { //@Query 使用jpql的方式查询。?1代表参数的占位符,其中1对应方法中的参数索引 @Query(value = "from Customer where custName like %?1%") public Customer findCustomer(String custName); /* * 对于多个占位符 * 默认情况下,占位符的位置要和参数的位置保持一致 * 可以自己指定占位符的位置 * 在 ?数字 来指定占位取值来源 * */ @Query(value = "from Customer where custName = ?2 and custId = ?1") public Customer findCustIdName(Long id, String name); //修改需要在使用 @Query 的同时,用 @Modifying 来将该操作标识为修改查询 @Query(value = "update Customer set custName = ?1 where custId = ?2") @Modifying public void updateCustomer(String custName, Long custId); /** * sql查询 * nativeQuery : 使用本地sql的方式查询 */ @Query(value = "select * from cst_customer", nativeQuery = true) public List<Customer> findSql(); /** * sql查询:模糊查询 * 注意:占位符 */ @Query(value = "select * from cst_customer where cust_name like %?1%", nativeQuery = true) public List<Customer> findSqlByCustName(String name); /* * 方法名的约定 * findBy:查询 * 对象名中的属性名(首字母大写):查询条件 * custName * 默认的情况下使用等于的方式进行查询 * 特殊的查询方式 * 在springDataJpa的运行阶段: * 会根据方法名称进行解析 findBy from xxx(实体类) * * 1. findBy + 属性名称(根据属性名称进行完成匹配的查询=) * 2. findBy +属性名称+“查询方式(Like| isnull) * findByCustNameLike * 3. 多条件查询 * findBy +属性名+ "查询方式"+ "多条件的连接符(and|or)" +属性名+"查询方式" * */ public Customer findByCustName(String custName); public List<Customer> findByCustNameLike(String custName); //使用用户名称模糊匹配和用户地址精准匹配 public List<Customer> findByCustNameLikeAndCustAddress(String custName,String custAddress); }
JpqlTest.java(测试代码)
package cn.kt.test;/* *Created by tao on 2020-05-04. */ import cn.kt.dao.CustomerDao; import cn.kt.domain.Customer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) //声明单元测试 @ContextConfiguration(locations = "classpath:applicationContext.xml") public class JpqlTest { @Autowired private CustomerDao customerDao; @Test public void TestFindCustomer() { Customer customer = customerDao.findCustomer("左眼"); System.out.println(customer); } @Test public void TestFindCustIdName() { Customer customer = customerDao.findCustIdName(2l, "Nick"); System.out.println(customer); } /* * 测试jpq1的更新操作 * springDataJpa中 使用jpq1完成更新/删除操作 * 注意:需要手动添加事务的支持 * 默认会执行结束之后,回滚事务 @Rollback :设置是否自动回滚 false| true * */ @Test @Transactional @Rollback public void TestUpdateCustomer() { customerDao.updateCustomer("红发香克斯", 8l); } @Test public void TestFindSql() { List<Customer> sql = customerDao.findSql(); for (Customer customer : sql) { System.out.println(customer); } } @Test public void TestFindSqlByCustName() { List<Customer> customers = customerDao.findSqlByCustName("左眼"); for (Customer customer : customers) { System.out.println(customer); } } /*测试命名规则的查询*/ @Test public void TestFindByCustName() { Customer nick = customerDao.findByCustName("Nick"); System.out.println(nick); } /*测试命名规则的模糊查询*/ @Test public void TestFindByCustNameLike() { List<Customer> byCustNameLike = customerDao.findByCustNameLike("左眼%"); for (Customer customer : byCustNameLike) { System.out.println(customer); } }/*测试命名规则的模糊查询*/ @Test public void TestFindByCustNameLikeAndCustAddress() { List<Customer> customers = customerDao.findByCustNameLikeAndCustAddress("左眼%","江西赣州"); for (Customer customer : customers) { System.out.println(customer); } } }
以上有三种方法可以实现复杂的查询,这其中Jpql语句必须掌握,因为这种方法最具有面向对象的思想