SpringDataJpa的基本使用
1.什么是SpringDataJpa(了解)
2.SpringDataJpa的基本使用(掌握)
3.JpaSpecificationExecutor(难点,尽量理解)
4.jpa-spac框架(掌握)
5.Query的抽取(思想)
6.SpringDataJpa的自定义扩展(难点–拷备完成)
不会再数据库创建表格,持久化到数据库
@MappedSuperclass
配置文件
<?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.zhx</groupId>
<artifactId>SpringDataJpa</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 指定框架使用版本 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<org.hibernate.version>4.3.8.Final</org.hibernate.version>
<spring-data-jpa.version>1.9.0.RELEASE</spring-data-jpa.version>
<com.fasterxml.jackson.version>2.5.0</com.fasterxml.jackson.version>
<org.slf4j.version>1.6.1</org.slf4j.version>
</properties>
<dependencies>
<!-- Spring的支持包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<!-- 引入web前端的支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- SpringMCV上传需要用到io包-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 文件上传用到的包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<!-- SpringMVC的json支持包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${com.fasterxml.jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${com.fasterxml.jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${com.fasterxml.jackson.version}</version>
</dependency>
<!-- hibernate的支持包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<!-- SpringData的支持包 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<!-- SpringData的擴展包 -->
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.1.1</version>
<!-- 把所有的依賴都去掉 -->
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<!-- 測試包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<!-- 这个scope 只能作用在编译和测试时,同时没有传递性。表示在运行的时候不添加此jar文件 -->
<scope>provided</scope>
</dependency>
<!-- 日志文件 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<!-- 代码生成器模版技术 freemark -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6</version>
</dependency>
<!-- shiro的支持包 权限框架 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.4.0</version>
<type>pom</type>
</dependency>
<!-- shiro与Spring的集成包 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<!-- poi支持的jar包 导入导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
<!-- 图片压缩功能 -->
<!-- 缩略图 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.6</version>
</dependency>
<!-- 定时调度 -->
<dependency>
<groupId>quartz</groupId>
<artifactId>quartz</artifactId>
<version>1.5.2</version>
</dependency>
<!-- 邮件支持 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.1</version>
</dependency>
</dependencies>
<build>
<finalName>yxb</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.15.v20140411</version>
<configuration>
<stopPort>9966</stopPort>
<stopKey>foo</stopKey>
<webAppConfig>
<contextPath>/</contextPath>
</webAppConfig>
</configuration>
在这里插入代码片 </plugin>
</plugins>
</build>
</project>
数据库配置
<?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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.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 service注解 repostory注解-->
<context:component-scan base-package="cn.zhx.aisell"></context:component-scan>
<!--jdbc.properties dataSource EntityManagerFactory Transaction-->
<!-- 加载配置jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置连接池dataSource bean生命周期方法 销毁方法close 用来连接之后 还给链接池-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 得到EntityManagerFactory 方言 链接池-->
<!-- 得到EntityManagerFactory-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- 配置属性 setDataSource-->
<property name="dataSource" ref="dataSource"></property>
<!-- 扫描实体类的配置 entity-->
<property name="packagesToScan" value="cn.zhx.aisell.domain"></property>
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- 是否显示sql-->
<property name="showSql" value="true"></property>
<!-- 是否创建表-->
<property name="generateDdl" value="true"></property>
<!--数据库方言-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"></property>
</bean>
</property>
</bean>
<!-- 事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<!-- 开启事务 扫描@Transaction这种注解-->
<tx:annotation-driven/>
<!-- springdatajpa配置 引入事务和实体管理工厂-->
<jpa:repositories base-package="cn.zhx.aisell.repository"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory">
</jpa:repositories>
</beans>
数据库链接账户
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///aisell
jdbc.username=root
jdbc.password=123456
公共方法抽取
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class BaseTest {
}
查询
public class TestJpaSpec extends BaseTest{
@Autowired
private EmployeeRepository1 employeeRepository1;
//查询
@Test
public void testSpec()throws Exception{
List<Employee> all = employeeRepository1.findAll(new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?>cq, CriteriaBuilder cb) {
//拿到字段操作
Path path = root.get("username");
//构建查询 like
Predicate p = cb.like(path, "%1%");
return p;
}
});
for (Employee employee : all) {
System.out.println(employee);
}
}
@Test
public void testSpec1()throws Exception{
List<Employee> employees = employeeRepository1.findAll(new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
//拿到操作字段
Path path1 = root.get("username");
Path path2 = root.get("age");
//构建查询 like
Predicate p1 = cb.like(path1, "%1%");
Predicate p2 = cb.gt(path2, 25);
//where username like %1% and age > 25
CriteriaQuery<?> where = cq.where(p1, p2);
return where.getRestriction();
}
});
for (Employee employee : employees) {
System.out.println(employee);
}
}
//条件+分页排序
@Test
public void testSpec2()throws Exception{
Specification<Employee> spec = new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
//拿到字段
Path path1 = root.get("username");
Predicate like = cb.like(path1, "1");
return like;
}
};
Sort sort = new Sort(Sort.Direction.ASC, "age");
PageRequest pageRequest = new PageRequest(0, 5, sort);
Page<Employee> all = employeeRepository1.findAll(spec, pageRequest);
for (Employee employee : all){
System.out.println(employee);
}
}
}
使用第三方插件包 对原本springdatajpa的动态条件查询(JpaSpecificationExecutor)进行扩展2种查询方法
public class TestJpaSpec1 extends BaseTest{
@Autowired
private EmployeeRepository1 employeeRepository1;
//高级查询和分页
@Test
public void testSpec1()throws Exception{
Employee employee = new Employee();
//模糊查询
employee.setUsername("%1%");
employee.setAge(25);
Specification<Employee> spec = Specifications.<Employee>and()
.like(StringUtils.isNotBlank(employee.getUsername()), "username", employee.getUsername())
.gt(employee.getAge() != null, "age", employee.getAge())
.build();
List<Employee> all = employeeRepository1.findAll(spec);
for (Employee employee1 : all){
System.out.println(employee1);
}
}
@Test
public void testSpec2()throws Exception{
Employee employee = new Employee();
employee.setUsername("1");
employee.setAge(25);
Sort sort = new Sort(Sort.Direction.ASC, "age");
PageRequest pageRequest = new PageRequest(0, 5, sort);
Specification<Employee> spec = Specifications.<Employee>and()
.like(StringUtils.isNotBlank(employee.getUsername()), "username", employee.getUsername())
.gt(employee.getAge() != null, "age", employee.getAge())
.build();
Page<Employee> all = employeeRepository1.findAll(spec, pageRequest);
for (Employee employee1:all){
System.out.println(employee1);
}
}
}
指定条件查询,排序,分页
ublic class TestJpaSpec2 extends BaseTest {
@Autowired
private EmployeeRepository1 employeeRepository1;
@Test
public void testSpringEvn() throws Exception {
EmployeeQuery employeeQuery = new EmployeeQuery();
employeeQuery.setUsername("1");
employeeQuery.setAge(18);
//指查询条件
Specification<Employee> spe = Specifications.<Employee>and().
like(StringUtils.isNotBlank(employeeQuery.getUsername()),
"username", "%" + employeeQuery.getUsername() + "%")
.gt(employeeQuery.getAge() != null, "age", employeeQuery.getAge())
.build();
//排序
Sort sort = null;
if (employeeQuery.getOrderByName() != null) {
String orderByName = employeeQuery.getOrderByName();
Sort.Direction direction = null;
if (employeeQuery.getOrderByType().equals("DESC")) {
direction = Sort.Direction.DESC;
} else {
direction = Sort.Direction.ASC;
}
//组装Sort
sort = new Sort(direction, orderByName);
}
//分页
Pageable pageable = new PageRequest(employeeQuery.getJpaPage(), employeeQuery.getPageSize(), sort);
Page<Employee> employees = employeeRepository1.findAll(spe, pageable);
for (Employee employee : employees) {
System.out.println(employee);
}
}
@Test
public void testSpec2()throws Exception{
EmployeeQuery employeeQuery = new EmployeeQuery();
employeeQuery.setUsername("1");
employeeQuery.setAge(18);
Specification spec = employeeQuery.createSpecification();
Sort sort = employeeQuery.createSort();
Pageable pageable = new PageRequest(employeeQuery.getJpaPage(), employeeQuery.getPageSize(), sort);
Page<Employee> lists = employeeRepository1.findAll(spec, pageable);
for (Employee employee : lists) {
System.out.println(employee);
}
}
}
public class TestPageAndSort extends BaseTest {
@Autowired
private EmployeeRepository employeeRepository;
//排序
@Test
public void testSort() throws Exception{
Sort sort = new Sort(Sort.Direction.DESC,"age","id");
List<Employee> employees = employeeRepository.findAll(sort);
for (Employee employee : employees) {
System.out.println(employee);
}
}
//分页
@Test
public void testPage() throws Exception{
//page =0 表示第一页 size 每页条数
Pageable pageable = new PageRequest(26, 5);
Page<Employee> employees = employeeRepository.findAll(pageable);
System.out.println("totalEmlements:"+employees.getTotalElements());//总条数
System.out.println("totalPages:"+employees.getTotalPages());//27
System.out.println("content:"+employees.getContent());//当前页内容数据
System.out.println("number:"+employees.getNumber());//number+1 当前页
System.out.println("numberofElements:"+employees.getNumberOfElements());//当前页条数
System.out.println("size:"+employees.getSize());//每页条数
for (Employee employee : employees) {
System.out.println(employee);
}
}
//分页+排序
@Test
public void testPageAndPage() throws Exception{
//page =0 表示第一页 size 每页条数
Sort sort = new Sort(Sort.Direction.DESC,"age");
Pageable pageable = new PageRequest(0, 5,sort);
Page<Employee> employees = employeeRepository.findAll(pageable);
for (Employee employee : employees) {
System.out.println(employee);
}
}
}
public class TestQuery extends BaseTest{
@Autowired
private EmployeeRepository employeeRepository;
//按照规范查询
@Test
public void testQuery()throws Exception{
List<Employee> x = employeeRepository.findEmployeeByUsername("x");
for (Employee employee : x) {
System.out.println(employee);
}
}
//按照规范查询
@Test
public void testQuery1()throws Exception{
List<Employee> employeeByUsernameLike = employeeRepository.findEmployeeByUsernameLike("%s%");
for (Employee employee : employeeByUsernameLike) {
System.out.println(employee);
}
}
//Query注解查询
@Test
public void testQuery2() throws Exception{
List<Employee> empByUsername = employeeRepository.findEmpByUsername("%1%");
for (Employee emp : empByUsername) {
System.out.println(emp);
}
}
//根据顺序来查询
@Test
public void testQuery3() throws Exception{
List<Employee> employees = employeeRepository.query02("%b%", "%2%");
for (Employee emp : employees) {
System.out.println(emp);
}
}
//查询多条
@Test
public void testQuery4() throws Exception{
List<Employee> emps= employeeRepository.query03("b","%2%");
for (Employee emp : emps) {
System.out.println(emp);
}
}
//查询一条
@Test
public void testQuery5() throws Exception{
System.out.println(employeeRepository.query04());
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestSpringDataJpa {
@Autowired
private EmployeeRepository employeeRepository;
//查询
@Test
public void testJpa() throws Exception{
List<Employee> lists = employeeRepository.findAll();
System.out.println(employeeRepository.getClass());
for (Employee employee :lists ) {
System.out.println(employee);
}
}
// 批量查询 List<T> findAll(Iterable<ID> var1);
//select * from where employee0_.id in (? , ? , ?)
@Test
public void testfindAll() throws Exception{
List lists = Arrays.asList(5L,2L,3L);
List<Employee> list = employeeRepository.findAll(lists);
for (Employee o : list) {
System.out.println(o);
}
}
//查询一条数据
@Test
public void testFindOne() throws Exception{
Employee employee = employeeRepository.findOne(1L);
System.out.println(employee);
}
//保存
@Test
public void testsave() throws Exception{
Employee employee = new Employee();
employee.setUsername("袁旭");
employee.setPassword("zzz");
employee.setAge(28);
employeeRepository.save(employee);
}
//修改 如果有id 就修改 没有id 就新增
@Test
public void testUpdate() throws Exception{
Employee employee = new Employee();
employee.setId(274L);
employee.setUsername("袁旭");
employee.setPassword("xxx");
employee.setAge(38);
employeeRepository.save(employee);
}
//指定删除
@Test
public void testDelete() throws Exception{
employeeRepository.delete(274L);
}
//批量删除 -- 经过优化 性能高一点 where id=1 or id=2
@Test
public void testDeleteInBatch() throws Exception{
// List<Long> ids = Arrays.asList(272L, 273L);
List<Employee> list = employeeRepository.findAll(Arrays.asList(272L, 273L));
employeeRepository.deleteInBatch(list);
}
//批量删除 每删除一条就要发一条sql 不推荐使用
@Test
public void testDeleteALL() throws Exception{
List<Employee> list = employeeRepository.findAll(Arrays.asList(262L, 263L));
employeeRepository.delete(list);//多条sql
}
@Test
public void testCount() throws Exception{
System.out.println(employeeRepository.count());
}
}
public class TestSpringDataJpaCRUD extends BaseTest {
@Autowired
private EmployeeRepository employeeRepository;
//查询所有
@Test
public void testFindAll() throws Exception{
List<Employee> employees = employeeRepository.findAll();
for (Employee employee : employees) {
System.out.println(employee);
}
}
//批量查询
@Test
public void testFindAll1() throws Exception{
List ids = Arrays.asList(1L,2L,3L);
List<Employee> employees = employeeRepository.findAll(ids);
for (Employee employee : employees) {
System.out.println(employee);
}
}
}