SpringDataJPA概述:
Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!
Spring Data JPA 让我们解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作过程中,推荐使用Spring Data JPA + ORM(如:hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使数据库层操作更加简单,方便解耦。
SpringDataJPA特性:
SpringData Jpa 极大简化了数据库访问层代码。 如何简化的呢? 使用了SpringDataJpa,我们的dao层中只需要写接口,就自动具有了增删改查、分页查询等方法。
springDataJpa,jpa规范和hibernate之间的关系说明
知识概述
JPA是一套规范,内部是有接口和抽象类组成的。hibernate是一套成熟的ORM框架,而且Hibernate实现了JPA规范,所以也可以称hibernate为JPA的一种实现方式,我们使用JPA的API编程,意味着站在更高的角度上看待问题(面向接口编程)
Spring Data JPA是Spring提供的一套对JPA操作更加高级的封装,是在JPA规范下的专门用来进行数据持久化的解决方案。
hibernate才是真正干活的,它内部也封装了JDBC
SpringDataJPA的实现hibernate的测试
一、pom.xml的引入依赖
<properties>
<spring.version>5.0.2.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.12</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>${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>
<!-- 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>${spring.version}</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>
二、resource下面的配置文件
<?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"/>
<!--jdbc:mysql:///test 其中/代表ip地址是本地,端口是默认-->
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
<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.itcast.entity"/>
<!--JPA的实现厂家-->
<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"/>
<!--指定数据库类型-->
<!--value中为什么是MYSQL大写呢?可以点击name的值database进去可以看到相对应的值-->
<!--这里用到了枚举-->
<property name="database" value="MYSQL"/>
<!--指定方言-->
<!--如果想要更换Oracle的方言,可以点击MySQLDialect进去以后,可以在所在包内选择Oracle的方言-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
<!--是否显示SQL-->
<property name="showSql" value="true"/>
</bean>
</property>
<!--jpa的方言:高级的特性-->
<property name="jpaDialect">
<!--配置了这个以后,说明springdata jpa 也有了hibernate的高级特性-->
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<!-- 3.事务管理器-->
<!-- JPA事务管理器 -->
<!--PlatformTransactionManager 这是一个接口,通过这个接口来找对应的实现-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 整合spring data jpa-->
<!--base-package=指定的是spring整合JPA的dao的包-->
<!--transaction-manager-ref=指定的是事务的管理-->
<!--entity-manager-factory-ref=指定的底层还是用的jpa配置-->
<jpa:repositories base-package="cn.itcast.dao"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
<!-- 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.itcast.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
<!--配置spring的包扫描,是扫描的spring的注解-->
<context:component-scan base-package="cn.itcast"></context:component-scan>
<!--组装其它 配置文件-->
</beans>
三、实体类的搭建
package cn.itcast.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* 所有的注解都是使用JPA的规范提供的注解,
* 所以在导入注解包的时候,一定要导入javax.persistence下的
*
*/
@Entity //声明实体类
@Table(name="cst_customer") //建立实体类和表的映射关系
public class Customer implements Serializable {
/**
* @GeneratedValue:配置主键的生成策略
* strategy
* GenerationType.IDENTITY:自增,mysql
* *底层数据库必须支持自动增长(底层数据库支持的自动增长方式,对id自增)
* GenerationType.SEQUENCE: 序列,Oracle
* *底层数据库必须支持序列
* GenerationType.TABLE:jpa提供的一种机制,通过一张数据库表的形式帮助我们完成主键自增
* GenerationType.AUTO: 由程序自动的帮助我们选择主键生成策略
*/
@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;
//省去getter和setter方法
}
四、接口的定义(一个接口的定义只能对应一个实体类)
import cn.itcast.entity.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> {
}
五、测试
import cn.itcast.dao.CustomerDao;
import cn.itcast.entity.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;
//声明spring提供的单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:META-INF/persistence.xml")
public class CustomerDaoTest {
@Autowired
private CustomerDao customerDao;
// 保存操作
@Test
public void save01() {
Customer c = new Customer();
c.setCustAddress("aaaaaaaa");
customerDao.save(c);
}
//修改操作
/**
* 修改客户:调用save(obj)方法
* 对于save方法的解释:如果执行此方法是对象中存在id属性,即为更新操作会先根据id查询,再更新
* 如果执行此方法中对象中不存在id属性,即为保存操作。
*
*/
@Test
public void update01(){
//根据id查询,类型以实体类中的类型查询
Customer one = customerDao.findOne(5l);
one.setCustAddress("ccc");
customerDao.save(one);
}
/**
* 根据id删除:调用delete(id)方法
*/
@Test
public void del01(){
customerDao.delete(5l);
}
/**
* 根据id查询:调用findOne(id)方法
*/
@Test
public void findById(){
Customer one = customerDao.findOne(4l);
System.out.println(one);
}
/**
* save方法要想执行修改操作,必须先查出来再修改。
* 否则的话一条记录全部修改
*/
@Test
public void saveDemo(){
Customer aa = new Customer();
Customer one = customerDao.findOne(4l);
one.setCustAddress("年后");
customerDao.save(one);
}
@Test
public void findAll(){
List<Customer> all = customerDao.findAll();
for (Customer customer :all){
System.out.println(customer);
}
}
/**
* count方法 , 查询到统计数量
*/
@Test
public void countDemo(){
long count = customerDao.count();
System.out.println(count);
}
/**
* 测试:判读id为4的客户是否存在
* 1、可以查询以下id为4的客户
* 如果值为空,代表不存在,如果不为空,代表存在
* 2、判断数据库中id为4的客户的数量
* 如果数量为0,代表不存在,如果大于0,代表存在
*/
@Test
public void exitsDemo(){
boolean exists = customerDao.exists(4l);
System.out.println(exists);
}
/**
*根据id从数据库查询
* @Transactional:保证getOne正常运行
* findOne:
* em.find() :立即加载
* getOne:
* em.getReference :延迟加载
* 返回的是一个客户的动态代理对象
* 什么时候用,什么时候查询
*/
@Test
@Transactional
public void getOneDemo(){
Customer one = customerDao.getOne(4l);
System.out.println(one);
}
}
六、springDataJpa的运行过程和原理剖析
1 、通过JdkDynamicAopProxy的invoke方法创建一个动态代理对象
2、SimpleJpaRepository当中封装了JPA的操作(借助JPA的api完成数据库的CRUD)
3、通过hibernate完成数据库操作(封装了jdbc)
七、jpql语句的测试
复杂查询
i.借助接口中的定义好的方法完成查询
findOne(id):根据id查询
ii.jpql的查询方式 jpql
: jpa query language (jpq查询语言) 特点:语法或关键字和sql语句类似 查询的是类和类中的属性
* 需要将JPQL语句配置到接口方法上
1.特有的查询:需要在dao接口上配置方法
2.在新添加的方法上,使用注解的形式配置jpql查询语句
3.注解 : @Queryiii.sql语句的查询
1.特有的查询:需要在dao接口上配置方法
2.在新添加的方法上,使用注解的形式配置sql查询语句
3.注解 : @Query
value :jpql语句 | sql语句
nativeQuery :false(使用jpql查询) | true(使用本地查询:sql查询)
是否使用本地查询
iiii.方法名称规则查询
*是对jpql查询,更加深入一层的封装 *我们只需要按照SpringDataJpa提供的方法名称规则定
义方法,不需要再配置jpql语句,完成查询 *
findBy开头: 代表查询
对象中属性名称(首字母大写) *含义:根据属性名称进行查询
接口的定义
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
/**
* 符合springdata JPA规范的dao层
*
* JpaRepository<实体类类型,主键类型>:用来完成基本CRUD操作
* JpaSpecificationExecutor<实体类类型>:用于复杂查询(分页等查询操作)
*/
public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
/**
* 案例:根据客户名称查询客户
* jpql: from Customer where custName = ?
*
* 配置jpql语句,使用的@Query 注解
* @param custName
* @return
*/
@Query(value = "from Customer where custName = ?")
public Customer findJpql(String custName);
/**
* 案例根据客户名称和id来查询
* jpql : from Customer where custName = ? and custId = ?
* 配置jpql语句,使用的@Query 注解
* 对于多个占位符,默认情况下参数的位置和占位符的位置是一致的,
* 当然可以自定义位置,在?后边加指定位置的索引数字
*/
@Query(value = "from Customer where custName = ?2 and custId = ?1")
public Customer findbyIdandName(Long id,String name);
/**
* jpql语句也可以进行更新操作
* sql: update cust_customer set cust_name = ? where cust_id = ?
* jpql: update Customer set custName = ? where custId = ?
*
* @Query代表查询
* @Modifying代表更新操作
*/
@Query(value = " update Customer set custName = ? where custId = ? ")
@Modifying
public void updateDemo(String name,Long id);
/**
* 用SQL语句查询全部
* 需要注意的是要加 nativeQuery = true
*/
@Query(value = "select * from cst_customer",nativeQuery = true)
public List<Object []> selectDemo();
/**
* 用SQL语句条件查询
* SQL:select * from cst_customer where cust_name = ? % a %
*/
@Query(value = "select * from cst_customer where cust_name like ?",nativeQuery = true)
public List<Object []> selectByWhere(String name);
/**
* 按照约定的方法名 findBy_ 对象的属性名称首字母大写
* 方法名的约定:
* findBy: 查询
* 对象中的属性名(首字母大写) :查询的条件
* 1、findBy + 属性名称 (根据属性名称进行完成匹配的查询=)
* 特殊查询
* 2、findBy + 属性名称 + “查询方式 (Like | isnull)”
* 3、多条件查询
* findBy + 属性名 + “查询方式” + “多条件的连接符(and | or)” + 属性名 + “查询方式”
*/
public Customer findByCustName(String custName);
//使用客户名称模糊匹配和客户所属行业精准匹配的查询
public Customer findByCustNameLikeAndCustIndustry(String name,String ind);
}
测试代码
//声明spring提供的单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:META-INF/persistence.xml")
public class JpqlTest {
@Autowired
private CustomerDao customerDao;
@Test
public void jqplDemo(){
Customer cc = customerDao.findJpql("bbbb");
System.out.println(cc);
}
@Test
public void jqplDemo2(){
Customer cc2 = customerDao.findbyIdandName(2l,"bbbb");
System.out.println(cc2);
}
/**
* 测试jpql的更新操作时,
* springDataJpa中使用jpql完成 更新/删除操作时
* -需要手动添加事务的支持
* -默认会执行结束后,回滚事务
*/
@Test
@Transactional
@Rollback(value = false)
public void updateDemo(){
customerDao.updateDemo("aaa", 2l);
}
@Test
public void selectDemo(){
List<Object[]> customers = customerDao.selectDemo();
for (Object[] customer : customers) {
for (Object o : customer) {
System.out.println(o);
}
}
}
@Test
public void selectDemoByWhere(){
List<Object[]> objects = customerDao.selectByWhere("%a%");
for (Object[] object : objects) {
for (Object o : object) {
System.out.println(o);
}
System.out.println(object);
}
}
/**
* 根据约定的方法名来查询
*
*/
@Test
public void seleBy(){
Customer aaa = customerDao.findByCustName("aaa");
System.out.println(aaa);
}
/**
* 多条件的模糊匹配
*/
@Test
public void seleByy(){
Customer customer = customerDao.findByCustNameLikeAndCustIndustry("%a%", "不知道");
System.out.println(customer);
}
}