SpringData JPA概述:
SpringData JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作。
它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 SpringData JPA 可以极大提高开发效率!
SpringData JPA 让我们解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作工程中,
推荐使用SpringData JPA + ORM(如:hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使数据库层操作更加简单,方便解耦
SpringData JPA的快速入门:
1.引入SpringData JPA和操作数据库相关的坐标
<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 AOP -->
<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> <!-- spring IOC -->
<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-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency> <!-- spring对orm框架的支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency> <!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency> <!-- hibernate对JPA的实现 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency> <!-- c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency> <!-- log -->
<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> <!-- 数据库驱动 -->
<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> <!-- spring 测试 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency> <!-- el 使用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>
</dependencies>
2.整合Spring Data JPA与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"
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"> <!-- 开启注解扫描 -->
<context:component-scan base-package="com.fgy"></context:component-scan> <!-- 创建entityManagerFactory对象交给spring容器管理-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置扫描实体类所在的包 -->
<property name="packagesToScan" value="com.fgy.domain"></property>
<!-- 配置JPA的实现厂家 -->
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
</property>
<!--jpa的供应商适配器 -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--配置是否自动创建数据库表 -->
<property name="generateDdl" value="true" />
<!--指定数据库类型 -->
<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>
<!-- 注入jpa的配置信息
加载jpa的基本配置信息和jpa实现方式(这里是hibernate)的配置信息 -->
<property name="jpaProperties">
<props>
<!-- 自动创建数据库表 create update none -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 格式化SQL语句 -->
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean> <!-- 创建数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean> <!-- 整合spring data jpa -->
<jpa:repositories base-package="com.fgy.dao" transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"></jpa:repositories> <!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 配置事务属性 -->
<tx:attributes>
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!-- 配置aop -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut id="pt" expression="execution(* com.fgy.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>
3.使用JPA注解配置实体类和表的映射关系
@Entity
@Table(name = "cst_customer")
public class Customer implements Serializable { @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; /*************** get和set方法 ***************/
4.编写符合Spring Data JPA规范的Dao层接口
Spring Data JPA是spring提供的一款对于数据访问层(Dao层)的框架,
使用Spring Data JPA,只需要按照框架的规范提供dao接口,不需要实现类就可以完成数据库的增删改查、分页查询等方法的定义,极大的简化了我们的开发过程
在Spring Data JPA中,对于定义符合规范的Dao层接口,需要遵循以下几点:
1.创建一个Dao层接口,并实现JpaRepository和JpaSpecificationExecutor
2.提供相应的泛型
/**
* 客户持久层接口
*
* JpaRepository<实体类类型,主键类型>:用来完成基本CRUD操作
* JpaSpecificationExecutor<实体类类型>:用于复杂查询(分页等查询操作)
*/
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> { }
5.测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class CustomerDaoTest { @Autowired
private CustomerDao customerDao; @Test
public void testFindAll() {
List<Customer> customers = customerDao.findAll();
for (Customer customer : customers) {
System.out.println(customer);
}
}
}
测试其他方法:
/**
* 修改客户:调用save(obj)方法
* 如果执行此方法,参数对象中存在id属性,即为更新操作,会先根据id查询,再更新
* 如果执行此方法中对象中不存在id属性,即为保存操作
*/
@Test
public void testSave() {
// 根据id查询id为1的客户
Customer c1 = customerDao.findOne(5L);
// 修改客户名称
c1.setCustName("不三不四");
// 更新数据
// customerDao.save(c1); Customer c2 = new Customer();
c2.setCustName("小倩");
// 插入数据
customerDao.save(c2);
}
/**
* 根据id查询一条记录
*/
@Test
public void testFindById() {
Customer customer = customerDao.findOne(5L);
System.out.println(customer);
}
/**
* 删除一条记录
*/
@Test
public void testDelete() {
customerDao.delete(5L);
}
在 JpaRepository 接口以及父接口(灰色为父接口继承过来的方法)中已经声明了多个操作数据库的方法,可以直接使用
JpaSpecificationExecutor接口的方法
Specification接口中只定义了如下一个方法:
构造查询条件
/**
* root :Root接口,代表查询的根对象,可以通过root获取实体中的属性
* query :代表一个顶层查询对象,用来自定义查询
* cb :用来构建查询,此对象里有很多条件方法
**/
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb);
cb中方法的对应关系:
使用Specifications完成条件查询:
1.持久层接口
/**
* 客户持久层接口
*
* JpaRepository<实体类类型,主键类型>:用来完成基本CRUD操作
* JpaSpecificationExecutor<实体类类型>:用于复杂查询(分页等查询操作)
*/
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
}
2.测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpecTest { @Autowired
private CustomerDao customerDao; /**
* 根据条件查询单个对象
* 根据客户名称查询
*/
@Test
public void testSpec() {
Specification<Customer> spec = new Specification<Customer>() {
@Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> custName = root.get("custName");
// 构造查询条件
Predicate predicate = cb.equal(custName, "小明");// 进行精准的匹配
return predicate;
}
};
Customer c = customerDao.findOne(spec);
System.out.println(c);
} /**
* 多条件查询
* 根据客户名和客户行业查询
*/
@Test
public void testSpec2() {
Customer c = customerDao.findOne(new Specification<Customer>() {
@Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> custName = root.get("custName");
Path<Object> custIndustry = root.get("custIndustry");
Predicate p1 = cb.equal(custName, "小倩");
Predicate p2 = cb.equal(custIndustry, "教育");
// 将多个查询条件组合到一起
// 与的形式
return cb.and(p1, p2);
// 或的形式
// return cb.or(p1, p2);
}
});
System.out.println(c);
} /**
* 根据客户名模糊匹配
* gt,lt,ge,le,like : 得到path对象,根据path指定比较的参数类型,再去进行比较
* 指定参数类型:path.as(类型的字节码对象)
*/
@Test
public void testSpec3() {
List<Customer> customers = customerDao.findAll(new Specification<Customer>() {
@Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> custName = root.get("custName");
return cb.like(custName.as(String.class), "小%");
}
});
for (Customer customer : customers) {
System.out.println(customer);
}
} /**
* 根据条件查询,然后排序
*/
@Test
public void testSpec4() {
Specification<Customer> spec = new Specification<Customer>() {
@Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> custName = root.get("custName");
return cb.like(custName.as(String.class), "小%");
}
};
// 参数1:排序顺序(正序,倒序)
// 参数2:排序属性名称
Sort sort = new Sort(Sort.Direction.DESC, "custId"); List<Customer> customers = customerDao.findAll(spec, sort);
for (Customer customer : customers) {
System.out.println(customer);
}
} /**
* 分页查询
* findAll(Specification, Pageable)
* 参数1:查询条件
* 参数2:分页参数(查询页码,每页查询条数)
* findAll(Pageable) 没有条件的分页
*/
@Test
public void testSpec5() {
Specification spec = null;
Pageable pageable = new PageRequest(0, 2);
Page<Customer> page = customerDao.findAll(spec, pageable);
List<Customer> customers = page.getContent(); // 得到数据集合列表
long totalCount = page.getTotalElements(); // 得到总记录数
int totalPages = page.getTotalPages();// 得到总页数 for (Customer customer : customers) {
System.out.println(customer);
}
System.out.println(totalCount);
System.out.println(totalPages);
} /**
* 根据条件统计记录
*/
@Test
public void testSpec6() {
long count = customerDao.count(new Specification<Customer>() {
@Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> industry = root.get("custIndustry");
return cb.isNull(industry);
}
});
System.out.println(count);
}
}