对Spring Data JPA做了一个基本的简介,包括springdatajpa与hibernate、jpa之间的关系;Spring Data JPA的入门案例环境的搭建、CRUD等操作。
SpringDataJPA的概述
Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!在JPA的基础上再做了一层封装。
特性:
Spring Data JPA 极大的简化了数据库访问层代码(持久层)。如何简化呢?使用了Spring Data JPA,我们的dao层只需要写接口,再配置包扫描,我们只需要调用接口对象,将会自动生成动态代理对象执行增删查改、分页等操作。
Spring Data JPA与JPA与hibernate之间的关系
JPA是一套规范,内部由接口和抽象类实现;hibernate是一套成熟的ORM框架,且hibernate实现了JPA规范,所以hibernate是JPA的一种实现方式,我们使用JPA中的API编程,意味着站在更高的角度看代问题(面向接口编程。)
Spring Data JPA是Spring提供的一套对JPA操作更加高级的封装。
Spring Data JPA快速入门
-
环境搭建
-
Maven工程
-
依赖
<?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>ctgu.rxz</groupId> <artifactId>springdataJpa01</artifactId> <packaging>pom</packaging> <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.12</version> <scope>test</scope> </dependency> <!-- spring beg --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</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>4.2.5.RELEASE</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.4.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> <!--springdatajpa的坐标--> <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> </project>
-
-
配置文件
- 1.配置数据库连接池
- 2.配置entityManageFactory对象交给Spring容器管理
- 1)配置实体类包扫描
- 2)配置JPA的实现厂家
- 3)配置JPA的供应适配器(指定数据库)
- 3.设置JPA事务管理器
- 4.整合Spring Data JPA,指定dao接口的包名称,声明要对此包下的dao接口进行动态代理
- 5.AOP事务管理
- 6.配置spring包扫描
<?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"> <!--spring和spring data jpa的配置--> <!--配置包扫描--> <context:component-scan base-package="ctgu"/> <!--1.配置数据库连接池--> <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/mybatis?characterEncoding=utf-8"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!--2.配置entityManageFactory对象交给spring容器管理 指定实体类所在的包名称--> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--i 配置的是扫描的包(实体类所在的包)--> <property name="packagesToScan" value="ctgu.pojo"/> <!--ii 配置Jpa的实现厂家--> <property name="persistenceProvider"> <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/> </property> <!--iii 配置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"/> <property name="showSql" value="true"/> </bean> </property> <!--配置Jpa的方言:高级的特性,不同的实现厂商有各自的特性,比如Hibernate--> <property name="jpaDialect"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/> </property> </bean> <!-- 3.JPA事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <!--4.整合spring dataJpa 指定dao接口的包名称 声明要对此包下的dao接口进行动态代理增强,生成simpleJpaRepository代理类--> <jpa:repositories base-package="ctgu.dao" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"/> <!--5.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> <!-- 6.aop--> <aop:config> <aop:pointcut id="pointcut" expression="execution(* cn.itcast.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/> </aop:config> </beans>
-
编写实体类,完成数据库和实体类之间的关系映射
- 1.配置实体类与表的映射关系(此pojo与数据库中的那一张表关系映射)
- @Entiy
- @Table(name=“数据库表的名称”)
- 2.实体类中属性与表中字段的映射关系
- @Id(“name”)数据库中的主键字段名
- @GeneratedValue(value)
- strategy=GenerationType.IDENTITY:自增 Mysql(底层数据库支持的自增长方式对id自增)
- strategy=GenerationType.SEQUENCE:序列 Oracle(底层数据库必须支持序列)
- strategy=GenerationType.TABLE:jpa提供的一种机制,通过一张数据库表的形式帮助我们完成自增
- strategy=GenerationType.AUTO:有程序自动的帮助我们选择主键生成策略
- @Column(name=“value”)数据库中表的字段名
注意:
默认@Column()配置是可以省略的,遵从驼峰式命名,也就是遇到大写字母会转成 ‘_’ ,但是如果配置下面的代码就不能省略了,属于无修改命名。
比如数据库中字段名是:user_name, 则对应实体类中写成 userName
package ctgu.pojo; import javax.persistence.*; @Entity @Table(name = "cst_customer") public class Customer { /** * @ Id声明主键的设置 * @ GeneratedValue配置主键是生成策略(自动增长) * GenerationType.IDENTITY * @ Column(name = "cust_id")数据库中表中字段的名字 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "cust_id") private Long custId; @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 = "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; } @Override public String toString() { return "Customer{" + "custId=" + custId + ", custName='" + custName + '\'' + ", custSource='" + custSource + '\'' + ", custIndustry='" + custIndustry + '\'' + ", custLevel='" + custLevel + '\'' + ", custAddress='" + custAddress + '\'' + ", custPhone='" + custPhone + '\'' + '}'; } public void setCustPhone(String custPhone) { this.custPhone = custPhone; } }
- 1.配置实体类与表的映射关系(此pojo与数据库中的那一张表关系映射)
-
编写dao接口
编写接口需要遵循:
- 实现JpaRepository<T,V>和JpaSpecificationExecutor接口。
- JpaRepository<T,V>:用于完成基本的CRUD操作。
- T:与数据库表对应的实体类型
- V:与数据库表对应实体的主键类型
- JpaSpecificationExecutor:与数据库表对应的实体类型
- JpaRepository<T,V>:用于完成基本的CRUD操作。
- 提供相应的泛型
package ctgu.dao;
import ctgu.pojo.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;
/**
* 符合springDataJpa的dao层接口规范
* JpaRepository<操作的实体类型,实体类型中的 主键 属性的类型>
* i 封装了基本的CRUD的操作
* JpaSpecificationExecutor<操作的实体类类型>
* i 封装了复杂查询(分页操作)
*/
public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
}
- 测试
package ctgu.test;
import ctgu.dao.CustomerDao;
import ctgu.pojo.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 org.springframework.transaction.annotation.Transactional;
import javax.persistence.Table;
import java.util.List;
/**
* 声明sping提供的单元测试环境
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class CustomerDaoTest {
@Autowired
private CustomerDao customerDao;
/**
* 根据id查询
* findOne(主键)
*/
@Test
public void findCustomer(){
Customer customer = customerDao.findOne(2L);
System.out.println(customer);
}
Spring Data JPA实现CRUD
完成上述入门案例后,我们对Customer类进行CRUD测试:
- save(Object)
/**
* save()保存或者更新
* 如果传入的对象没有id属性,那么就是保存;
* 如果存在id属性,就根据id查询后,再更新
*/
@Test
public void saveCustomer(){
Customer customer = new Customer();
customer.setCustAddress("湖北省宜昌市");
customer.setCustName("coderxz");
customerDao.save(customer);
}
@Test
public void updateCustomer(){
Customer customer = new Customer();
customer.setCustAddress("湖北省宜昌市");
customer.setCustName("coderxz(修改)");
customer.setCustId(5L);
customerDao.save(customer);
}
- findOne(主键属性)
/**
* 根据id查询
* findOne(主键)
*/
@Test
public void findCustomer(){
Customer customer = customerDao.findOne(2L);
System.out.println(customer);
}
- getOne(主键属性)
/**
* getOne(Long id)
* 测试时需要加入 @Transactional保证getOne()正常运行
* getOne和findOne有什么区别呢?em是EntityManager对象
* findOne()
* 底层调用 em.find() 立即加载
* getOne()
* 底层调用 em.getReference() 延迟加载
*/
@Test
@Transactional
public void getOne(){
Customer customer = customerDao.getOne(4L);
System.out.println(customer);
}
- delete(主键/对象)
/**
* 根据id进行删除
* 先根据id进行查询,如果有再执行删除 执行了select后执行delete
*/
@Test
public void deleteCustomer(){
customerDao.delete(2L);
}
- findAll()/count()/exists
@Test
public void findAllCustomer(){
List<Customer> list = customerDao.findAll();
for(Customer customer:list){
System.out.println(customer);
}
}
@Test
public void countCustomer(){
long count = customerDao.count();
System.out.println("统计客户总条数:"+count);
}
/**
* 测试用户是否存在
* 底层执行的是select
*/
@Test
public void ExistsCustomer(){
boolean exists = customerDao.exists(10L);
System.out.println("id为10的用户存在吗?"+exists);
}