资讯专栏INFORMATION COLUMN

慕课网_《轻松愉快之玩转SpringData》学习总结

skinner / 4102人阅读

摘要:时间年月日星期一说明本文部分内容均来自慕课网。慕课网教学示例源码个人学习源码第一章课程介绍课程介绍什么是主旨提供一个熟悉的一致的,基于框架的数据访问框架。

时间:2017年04月24日星期一
说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com
教学示例源码:https://github.com/zccodere/s...
个人学习源码:https://github.com/zccodere/s...

第一章:课程介绍 1-1 课程介绍

什么是Spring Data

</>复制代码

  1. 主旨:提供一个熟悉的、一致的,基于Spring框架的数据访问框架。
  2. 简化数据库的访问。
  3. 历史:2010年提出,作者Rod Johnso,Spring Source项目
  4. 网址:http://projects.spring.io/spring-data/#quick-start

Spring Data概览

Spring Data包含多个子项目

</>复制代码

  1. Spring Data JPA
  2. Spring Data Mongo DB
  3. Spring Data Redis
  4. Spring Data Solr

课程安排

</>复制代码

  1. 传统方式访问数据库
  2. Spring Data快速起步
  3. Spring Data JPA进阶
  4. Spring Data JPA高级
第二章:使用传统方式访问数据库 2-1 使用传统方式访问数据库

传统方式访问数据库

</>复制代码

  1. JDBC
  2. Spring JdbcTemplate
  3. 弊端分析
2-2 准备工作

JDBC

</>复制代码

  1. Connection
  2. Statement
  3. ResultSet
  4. Test Case

搭建开发环境

</>复制代码

  1. 创建maven项目
  2. 添加数据库驱动和单元测试依赖
  3. 数据库表的准备,使用mysql数据库

创建一个Java项目,POM文件如下:

</>复制代码

  1. 4.0.0
  2. com.zccoder
  3. myspringdata
  4. 1.0-SNAPSHOT
  5. UTF-8
  6. org.springframework
  7. spring-jdbc
  8. 4.3.6.RELEASE
  9. org.springframework
  10. spring-context
  11. 4.3.6.RELEASE
  12. org.springframework.data
  13. spring-data-jpa
  14. 1.11.3.RELEASE
  15. org.hibernate
  16. hibernate-entitymanager
  17. 5.2.10.Final
  18. mysql
  19. mysql-connector-java
  20. 5.1.38
  21. junit
  22. junit
  23. 4.10
  24. test

完成后的项目结构图:

2-3 JDBCUtil开发

开发JDBCUtil工具类

</>复制代码

  1. 获取Connection,关闭Connection、Statement、ResultSet
  2. 注意事项:配置的属性放置配置文件中,然后通过代码的方式将配置文件中的数据加载进来即可。

代码示例:

</>复制代码

  1. package com.myimooc.springdata.jdbc.util;
  2. import java.io.InputStream;
  3. import java.sql.*;
  4. import java.util.Properties;
  5. /**
  6. * JDBC工具类:
  7. * 1)获取Connection
  8. * 2)释放资源
  9. * Created by ZC on 2017/4/24.
  10. */
  11. public class JDBCUtils {
  12. /**
  13. * 获取Connection
  14. * @return 所获得到的JDBC的Connection
  15. */
  16. public static Connection getConnection() throws Exception{
  17. /**
  18. * 不建议大家把配置硬编码到代码中
  19. * 最佳实践:配置性的建议写到配置文件中
  20. * */
  21. // String url = "jdbc:mysql:///springdata";
  22. // String username = "root";
  23. // String password = "root";
  24. // String dirverClass = "com.mysql.jdbc.Driver";
  25. InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
  26. Properties properties = new Properties();
  27. properties.load(inputStream);
  28. String url = properties.getProperty("jdbc.url");
  29. String username = properties.getProperty("jdbc.username");
  30. String password = properties.getProperty("jdbc.password");
  31. String driverClass = properties.getProperty("jdbc.driverClass");
  32. Class.forName(driverClass);
  33. Connection connection = DriverManager.getConnection(url,username,password);
  34. return connection;
  35. }
  36. /**
  37. * 释放DB相关资源
  38. * @param resultSet
  39. * @param statement
  40. * @param connection
  41. */
  42. public static void release(ResultSet resultSet, Statement statement,Connection connection){
  43. if(resultSet != null ){
  44. try {
  45. resultSet.close();
  46. } catch (SQLException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. if(statement != null ){
  51. try {
  52. statement.close();
  53. } catch (SQLException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. if(connection != null ){
  58. try {
  59. connection.close();
  60. } catch (SQLException e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. }
  65. }
2-4 Dao开发

建立对象模型及DAO层开发。

代码演示:

1、对象模型

</>复制代码

  1. package com.myimooc.springdata.jdbc.domain;
  2. /**
  3. * Student实体类
  4. * Created by ZC on 2017/4/24.
  5. */
  6. public class Student {
  7. /** 主键ID */
  8. private Integer id;
  9. /** 姓名 */
  10. private String name;
  11. /** 年龄 */
  12. private int age;
  13. @Override
  14. public String toString() {
  15. return "Student{" +
  16. "id=" + id +
  17. ", name="" + name + """ +
  18. ", age=" + age +
  19. "}";
  20. }
  21. public Integer getId() {
  22. return id;
  23. }
  24. public void setId(Integer id) {
  25. this.id = id;
  26. }
  27. public String getName() {
  28. return name;
  29. }
  30. public void setName(String name) {
  31. this.name = name;
  32. }
  33. public int getAge() {
  34. return age;
  35. }
  36. public void setAge(int age) {
  37. this.age = age;
  38. }
  39. }

2、DAO接口

</>复制代码

  1. package com.myimooc.springdata.jdbc.dao;
  2. import com.myimooc.springdata.jdbc.domain.Student;
  3. import java.util.List;
  4. /**
  5. * StudentDAO访问接口
  6. * Created by ZC on 2017/4/24.
  7. */
  8. public interface StudentDao {
  9. /**
  10. * 获取所有学生
  11. * @return 所有学生
  12. */
  13. List listStudent();
  14. /**
  15. * 添加一个学生
  16. * @param student 待添加的学生
  17. */
  18. void saveStudent(Student student);
  19. }

3、DAO实现

</>复制代码

  1. package com.myimooc.springdata.jdbc.dao.impl;
  2. import com.myimooc.springdata.jdbc.dao.StudentDao;
  3. import com.myimooc.springdata.jdbc.domain.Student;
  4. import com.myimooc.springdata.jdbc.util.JDBCUtils;
  5. import java.sql.Connection;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. /**
  11. * StudentDAO访问接口实现类:通过最原始的JDBC的方式操作
  12. * Created by ZC on 2017/4/24.
  13. */
  14. public class StudentDaoImpl implements StudentDao {
  15. public List listStudent() {
  16. List studentList = new ArrayList();
  17. Connection connection = null;
  18. PreparedStatement preparedStatement = null;
  19. ResultSet resultSet = null;
  20. String sql = "select id,name,age from student";
  21. try {
  22. connection = JDBCUtils.getConnection();
  23. preparedStatement = connection.prepareStatement(sql);
  24. resultSet = preparedStatement.executeQuery();
  25. while(resultSet.next()){
  26. Integer id = resultSet.getInt("id");
  27. String name = resultSet.getString("name");
  28. Integer age = resultSet.getInt("age");
  29. Student student = new Student();
  30. student.setId(id);
  31. student.setName(name);
  32. student.setAge(age);
  33. studentList.add(student);
  34. }
  35. } catch (Exception e) {
  36. e.printStackTrace();
  37. } finally {
  38. JDBCUtils.release(resultSet,preparedStatement,connection);
  39. }
  40. return studentList;
  41. }
  42. public void saveStudent(Student student) {
  43. Connection connection = null;
  44. PreparedStatement preparedStatement = null;
  45. ResultSet resultSet = null;
  46. String sql = "insert into student(name,age) values(?,?)";
  47. try {
  48. connection = JDBCUtils.getConnection();
  49. preparedStatement = connection.prepareStatement(sql);
  50. preparedStatement.setString(1,student.getName());
  51. preparedStatement.setInt(2,student.getAge());
  52. preparedStatement.executeUpdate();
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. } finally {
  56. JDBCUtils.release(resultSet,preparedStatement,connection);
  57. }
  58. }
  59. }

4、单元测试

</>复制代码

  1. package com.myimooc.springdata.jdbc.dao;
  2. import com.myimooc.springdata.jdbc.dao.impl.StudentDaoImpl;
  3. import com.myimooc.springdata.jdbc.domain.Student;
  4. import org.junit.Test;
  5. import java.util.List;
  6. /**
  7. * StudentDao 单元测试类
  8. * Created by ZC on 2017/4/24.
  9. */
  10. public class StudentDaoImplTest {
  11. @Test
  12. public void listStudentTest(){
  13. StudentDao studentDao = new StudentDaoImpl();
  14. List studentList = studentDao.listStudent();
  15. for(Student student : studentList){
  16. System.out.println(student.toString());
  17. }
  18. }
  19. @Test
  20. public void saveStudentTest(){
  21. StudentDao studentDao = new StudentDaoImpl();
  22. Student student = new Student();
  23. student.setName("test");
  24. student.setAge(30);
  25. studentDao.saveStudent(student);
  26. }
  27. }
2-5 使用JdbcTemplate

Spring JdbcTemplate

</>复制代码

  1. 添加maven依赖
  2. DataSource & JdbcTemplate注入
  3. Test Case

代码演示:

1、创建DB配置文件

</>复制代码

  1. jdbc.url = jdbc:mysql:///springdata
  2. jdbc.username = root
  3. jdbc.password = root
  4. jdbc.driverClass = com.mysql.jdbc.Driver

2、创建配置文件类

</>复制代码

  1. package com.myimooc.springdata.jdbctemplate.config;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.ImportResource;
  4. import org.springframework.context.annotation.PropertySource;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. * 配置参数类
  8. * Created by ZC on 2017/4/24.
  9. */
  10. @PropertySource(value="classpath:db.properties")
  11. @Component
  12. public class Properties {
  13. @Value("${jdbc.driverClass}")
  14. private String jdbcDriverClass;
  15. @Value("${jdbc.url}")
  16. private String jdbcUrl;
  17. @Value("${jdbc.username}")
  18. private String jdbcUser;
  19. @Value("${jdbc.password}")
  20. private String jdbcPassword;
  21. @Override
  22. public String toString() {
  23. return "Properties{" +
  24. "jdbcDriverClass="" + jdbcDriverClass + """ +
  25. ", jdbcUrl="" + jdbcUrl + """ +
  26. ", jdbcUser="" + jdbcUser + """ +
  27. ", jdbcPassword="" + jdbcPassword + """ +
  28. "}";
  29. }
  30. public String getJdbcDriverClass() {
  31. return jdbcDriverClass;
  32. }
  33. public String getJdbcUrl() {
  34. return jdbcUrl;
  35. }
  36. public String getJdbcUser() {
  37. return jdbcUser;
  38. }
  39. public String getJdbcPassword() {
  40. return jdbcPassword;
  41. }
  42. }

3、配置DataSource、JdbcTemplate和Spring注解扫描

</>复制代码

  1. package com.myimooc.springdata.jdbctemplate.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.ComponentScan;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import org.springframework.jdbc.datasource.DriverManagerDataSource;
  8. /**
  9. * Created by ZC on 2017/4/24.
  10. */
  11. @Configuration
  12. @ComponentScan("com.myimooc.springdata.jdbctemplate")
  13. public class SpringConfig {
  14. @Autowired
  15. private Properties properties;
  16. @Bean
  17. DriverManagerDataSource getDriverManagerDataSource(){
  18. DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
  19. driverManagerDataSource.setDriverClassName(properties.getJdbcDriverClass());
  20. driverManagerDataSource.setUrl(properties.getJdbcUrl());
  21. driverManagerDataSource.setUsername(properties.getJdbcUser());
  22. driverManagerDataSource.setPassword(properties.getJdbcPassword());
  23. return driverManagerDataSource;
  24. }
  25. @Bean
  26. JdbcTemplate getJdbcTemplate(){
  27. JdbcTemplate jdbcTemplate = new JdbcTemplate();
  28. jdbcTemplate.setDataSource(getDriverManagerDataSource());
  29. return jdbcTemplate;
  30. }
  31. }

4、编写实体类

</>复制代码

  1. package com.myimooc.springdata.jdbctemplate.domain;
  2. /**
  3. * Student实体类
  4. * Created by ZC on 2017/4/24.
  5. */
  6. public class Student {
  7. /** 主键ID */
  8. private Integer id;
  9. /** 姓名 */
  10. private String name;
  11. /** 年龄 */
  12. private int age;
  13. @Override
  14. public String toString() {
  15. return "Student{" +
  16. "id=" + id +
  17. ", name="" + name + """ +
  18. ", age=" + age +
  19. "}";
  20. }
  21. public Integer getId() {
  22. return id;
  23. }
  24. public void setId(Integer id) {
  25. this.id = id;
  26. }
  27. public String getName() {
  28. return name;
  29. }
  30. public void setName(String name) {
  31. this.name = name;
  32. }
  33. public int getAge() {
  34. return age;
  35. }
  36. public void setAge(int age) {
  37. this.age = age;
  38. }
  39. }

5、DAO接口

</>复制代码

  1. package com.myimooc.springdata.jdbctemplate.dao;
  2. import com.myimooc.springdata.jdbctemplate.domain.Student;
  3. import java.util.List;
  4. /**
  5. * StudentDAO访问接口
  6. * Created by ZC on 2017/4/24.
  7. */
  8. public interface StudentDao {
  9. /**
  10. * 获取所有学生
  11. * @return 所有学生
  12. */
  13. List listStudent();
  14. /**
  15. * 添加一个学生
  16. * @param student 待添加的学生
  17. */
  18. void saveStudent(Student student);
  19. }

6、DAO实现

</>复制代码

  1. package com.myimooc.springdata.jdbctemplate.dao.impl;
  2. import com.myimooc.springdata.jdbctemplate.dao.StudentDao;
  3. import com.myimooc.springdata.jdbctemplate.domain.Student;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.jdbc.core.JdbcTemplate;
  6. import org.springframework.stereotype.Repository;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.Map;
  10. /**
  11. * StudentDAO访问接口实现类:通过 JdbcTemplate 的方式操作
  12. * Created by ZC on 2017/4/24.
  13. */
  14. @Repository
  15. public class StudentDaoImpl implements StudentDao {
  16. @Autowired
  17. private JdbcTemplate jdbcTemplate;
  18. public List listStudent() {
  19. List studentList = new ArrayList();
  20. String sql = "select id, name, age from student";
  21. List> mapList = jdbcTemplate.queryForList(sql);
  22. for (Map mapTemp : mapList) {
  23. Integer id = Integer.parseInt(mapTemp.get("id").toString());
  24. String name = mapTemp.get("name").toString();
  25. Integer age = Integer.parseInt(mapTemp.get("age").toString());
  26. Student student = new Student();
  27. student.setId(id);
  28. student.setName(name);
  29. student.setAge(age);
  30. studentList.add(student);
  31. }
  32. return studentList;
  33. }
  34. public void saveStudent(Student student) {
  35. String sql = "insert into student(name, age) value(?,?)";
  36. jdbcTemplate.update(sql,student.getName(),student.getAge());
  37. }
  38. }

7、单元测试类

</>复制代码

  1. package com.myimooc.springdata.jdbctemplate;
  2. import com.myimooc.springdata.jdbctemplate.config.SpringConfig;
  3. import com.myimooc.springdata.jdbctemplate.dao.StudentDao;
  4. import com.myimooc.springdata.jdbctemplate.domain.Student;
  5. import org.junit.After;
  6. import org.junit.Assert;
  7. import org.junit.Before;
  8. import org.junit.Test;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.context.ApplicationContext;
  11. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  12. import org.springframework.jdbc.core.JdbcTemplate;
  13. import org.springframework.jdbc.datasource.DriverManagerDataSource;
  14. import javax.sql.DataSource;
  15. import java.util.List;
  16. /**
  17. * 使用 JdbcTemplate 实现 StudentDao 单元测试类
  18. * Created by ZC on 2017/4/24.
  19. */
  20. public class StudentDaoTest {
  21. private ApplicationContext ctx = null;
  22. private StudentDao studentDao;
  23. @Before
  24. public void init(){
  25. ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  26. studentDao = ctx.getBean(StudentDao.class);
  27. }
  28. @After
  29. public void destroy(){
  30. ctx = null;
  31. }
  32. @Test
  33. public void listStudentTest(){
  34. List studentList = studentDao.listStudent();
  35. for (Student student : studentList){
  36. System.out.println(student.toString());
  37. }
  38. }
  39. @Test
  40. public void saveTest(){
  41. Student student = new Student();
  42. student.setName("test-spring-jdbcTemplate");
  43. student.setAge(25);
  44. studentDao.saveStudent(student);
  45. }
  46. }
2-6 弊端分析

弊端分析

</>复制代码

  1. DAO里面代码量太多
  2. DAO的实现有很多重复代码
  3. 开发分页和其它功能,需要重新进行封装
第三章:Spring Data快速入门 3-1 开发环境搭建

Spring Data JPA快速起步

</>复制代码

  1. 开发环境搭建
  2. Spring Data JPA HelloWorld开发

代码演示:

1、创建DB配置文件

</>复制代码

  1. jdbc.url = jdbc:mysql:///springdata
  2. jdbc.username = root
  3. jdbc.password = root
  4. jdbc.driverClass = com.mysql.jdbc.Driver

2、创建配置文件类

</>复制代码

  1. package com.myimooc.springdata.jpa.config;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.PropertySource;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * Created by ZC on 2017/4/24.
  7. */
  8. @PropertySource(value="classpath:db.properties")
  9. @Component
  10. public class PropertiesConfig {
  11. @Value("${jdbc.driverClass}")
  12. private String jdbcDriverClass;
  13. @Value("${jdbc.url}")
  14. private String jdbcUrl;
  15. @Value("${jdbc.username}")
  16. private String jdbcUser;
  17. @Value("${jdbc.password}")
  18. private String jdbcPassword;
  19. @Override
  20. public String toString() {
  21. return "Properties{" +
  22. "jdbcDriverClass="" + jdbcDriverClass + """ +
  23. ", jdbcUrl="" + jdbcUrl + """ +
  24. ", jdbcUser="" + jdbcUser + """ +
  25. ", jdbcPassword="" + jdbcPassword + """ +
  26. "}";
  27. }
  28. public String getJdbcDriverClass() {
  29. return jdbcDriverClass;
  30. }
  31. public String getJdbcUrl() {
  32. return jdbcUrl;
  33. }
  34. public String getJdbcUser() {
  35. return jdbcUser;
  36. }
  37. public String getJdbcPassword() {
  38. return jdbcPassword;
  39. }
  40. }

3、配置TransactionManager、EntityManagerFactory和Spring自动扫描注入

</>复制代码

  1. package com.myimooc.springdata.jpa.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.ComponentScan;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
  7. import org.springframework.jdbc.datasource.DriverManagerDataSource;
  8. import org.springframework.orm.jpa.JpaTransactionManager;
  9. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  10. import org.springframework.orm.jpa.vendor.Database;
  11. import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
  12. import org.springframework.transaction.PlatformTransactionManager;
  13. import org.springframework.transaction.annotation.EnableTransactionManagement;
  14. import java.util.Properties;
  15. /**
  16. * Spring配置类
  17. * Created by ZC on 2017/4/24.
  18. */
  19. // 声明为配置类
  20. @Configuration
  21. // 启用事务管理
  22. @EnableTransactionManagement
  23. // 启用自动扫描继承 JpaRepository 接口的类。
  24. // 注意,此注解需要配置 entityManagerFactory 和 transactionManager
  25. // 方式一:定义获取Bean方法名为 entityManagerFactory 和 transactionManager
  26. // 方式二:配置 @EnableJpaRepositories注解的 entityManagerFactoryRef 属性 为自定义获取Bean的方法名。
  27. @EnableJpaRepositories(basePackages = "com.myimooc.springdata.jpa")
  28. // 启用自动扫描 @Component 注解的Bean
  29. @ComponentScan(basePackages = "com.myimooc.springdata.jpa")
  30. public class SpringConfig{
  31. @Autowired
  32. private PropertiesConfig propertiesConfig;
  33. /**
  34. * 配置数据源
  35. * @return
  36. */
  37. @Bean
  38. public DriverManagerDataSource dataSource(){
  39. DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
  40. driverManagerDataSource.setDriverClassName(propertiesConfig.getJdbcDriverClass());
  41. driverManagerDataSource.setUrl(propertiesConfig.getJdbcUrl());
  42. driverManagerDataSource.setUsername(propertiesConfig.getJdbcUser());
  43. driverManagerDataSource.setPassword(propertiesConfig.getJdbcPassword());
  44. return driverManagerDataSource;
  45. }
  46. /**
  47. * 配置事务管理器 JpaTransactionManager
  48. * @return
  49. */
  50. @Bean(name="transactionManager")
  51. public PlatformTransactionManager transactionManager(){
  52. JpaTransactionManager transactionManager = new JpaTransactionManager();
  53. transactionManager.setDataSource(this.dataSource());
  54. transactionManager.setEntityManagerFactory(this.entityManagerFactory().getObject());
  55. return transactionManager;
  56. // return new DataSourceTransactionManager(this.dataSource());
  57. // return new JpaTransactionManager(this.entityManagerFactory().getObject());
  58. }
  59. /**
  60. * 配置JPA的 EntityManagerFactory
  61. * @return
  62. */
  63. @Bean
  64. public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
  65. LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
  66. entityManagerFactory.setDataSource(dataSource());
  67. HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
  68. jpaVendorAdapter.setGenerateDdl(true);
  69. jpaVendorAdapter.setDatabase(Database.MYSQL);
  70. entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
  71. entityManagerFactory.setPackagesToScan("com.myimooc.springdata.jpa");
  72. Properties jpaProperties = new Properties();
  73. // jpaProperties.setProperty("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy");
  74. jpaProperties.setProperty("hibernate.dialect","org.hibernate.dialect.MySQL5InnoDBDialect");
  75. jpaProperties.setProperty("hibernate.show_sql","true");
  76. jpaProperties.setProperty("hibernate.format_sql","true");
  77. jpaProperties.setProperty("hibernate.hbm2ddl.auto","update");
  78. entityManagerFactory.setJpaProperties(jpaProperties);
  79. return entityManagerFactory;
  80. }
  81. }

4、编写实体类:Employee

</>复制代码

  1. package com.myimooc.springdata.jpa.domain;
  2. import javax.persistence.*;
  3. /**
  4. * 雇员:先开发实体类,然后自动生成实体表
  5. * Created by ZC on 2017/4/24.
  6. */
  7. @Entity
  8. @Table(name = "test_employee")
  9. public class Employee {
  10. @Id
  11. @GeneratedValue
  12. private Integer id;
  13. @Column(length = 20)
  14. private String name;
  15. private Integer age;
  16. @Override
  17. public String toString() {
  18. return "Employee{" +
  19. "id=" + id +
  20. ", name="" + name + """ +
  21. ", age=" + age +
  22. "}";
  23. }
  24. public Integer getId() {
  25. return id;
  26. }
  27. public void setId(Integer id) {
  28. this.id = id;
  29. }
  30. public String getName() {
  31. return name;
  32. }
  33. public void setName(String name) {
  34. this.name = name;
  35. }
  36. public Integer getAge() {
  37. return age;
  38. }
  39. public void setAge(Integer age) {
  40. this.age = age;
  41. }
  42. }
3-2 起步程序开发

代码演示:

1、编写EmployeeRepository接口

</>复制代码

  1. package com.myimooc.springdata.jpa.repository;
  2. import com.myimooc.springdata.jpa.domain.Employee;
  3. import org.springframework.data.jpa.repository.Modifying;
  4. import org.springframework.data.jpa.repository.Query;
  5. import org.springframework.data.repository.Repository;
  6. import org.springframework.data.repository.query.Param;
  7. import org.springframework.transaction.annotation.Transactional;
  8. import java.util.List;
  9. /**
  10. * 使用 Repository 接口
  11. * Created by ZC on 2017/4/25.
  12. */
  13. // 方式二:使用 @RepositoryDefinition 注解
  14. // @RepositoryDefinition(domainClass = Employee.class,idClass = Integer.class)
  15. public interface EmployeeRepository extends Repository {//方式一:继承 Repository 接口
  16. /**
  17. * 获取雇员对象通过名称
  18. * @param name
  19. * @return
  20. */
  21. Employee findByName(String name);
  22. }

2、编写单元测试类:EmployeeRepositoryTest

</>复制代码

  1. package com.myimooc.springdata.jpa.repository;
  2. import com.myimooc.springdata.jpa.config.SpringConfig;
  3. import com.myimooc.springdata.jpa.domain.Employee;
  4. import com.myimooc.springdata.jpa.repository.EmployeeRepository;
  5. import com.myimooc.springdata.jpa.service.EmployeeService;
  6. import org.junit.After;
  7. import org.junit.Assert;
  8. import org.junit.Before;
  9. import org.junit.Test;
  10. import org.springframework.context.ApplicationContext;
  11. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  12. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. /**
  16. * EmployeeRepository单元测试类
  17. * Created by ZC on 2017/4/24.
  18. */
  19. public class EmployeeRepositoryTest {
  20. private ApplicationContext ctx = null;
  21. private EmployeeRepository employeeRepository = null;
  22. @Before
  23. public void init(){
  24. ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  25. employeeRepository = ctx.getBean(EmployeeRepository.class);
  26. }
  27. @After
  28. public void destroy(){
  29. ctx = null;
  30. }
  31. @Test
  32. public void entityManageFactoryTest(){
  33. LocalContainerEntityManagerFactoryBean entityManagerFactory = (LocalContainerEntityManagerFactoryBean)ctx.getBean(LocalContainerEntityManagerFactoryBean.class);
  34. Assert.assertNotNull(entityManagerFactory);
  35. }
  36. @Test
  37. public void findByNameTest(){
  38. System.out.println(employeeRepository);
  39. Employee employee = employeeRepository.findByName("cc");
  40. if( null == employee){
  41. System.out.println("查询数据为空");
  42. }else{
  43. System.out.println(employee.toString());
  44. }
  45. }
  46. }

Repository

</>复制代码

  1. Repository:Spring Data核心类
  2. RepositoryDefinition:使用该注解进行配置
  3. Repository Query Specification:查询时,方法命名不能乱写
  4. Query Annotation:使用该注解,可以实现原生SQL查询
  5. Update/Delete/Transaction:更新、删除操作,支持事务

Repository Hierarchy

</>复制代码

  1. CrudRepository:内置了新增、更新、删除、查询方法
  2. PagingAndSortingRespository:分页和排序
  3. JpaRepository
  4. JpaSpecificationExcutor
第四章:Spring Data JPA进阶 4-1 关于Repository接口

Repository接口详解

</>复制代码

  1. Repository接口是Spring Data的核心接口,不提供任何方法
  2. public interface Repository{}
  3. @RepositoryDefinition注解的使用

Repository类的定义:

</>复制代码

  1. 1)Repository是一个空接口,标记接口。没有包含方法声明的接口
  2. 2)如果我们定义的接口EmployeeRepository extends Repository,会被Spring管理。
  3. 如果我们自己的接口没有extends Repository,运行时会报错,没有这个Bean。
4-2 Repository子接口详解

Repository子接口详解

</>复制代码

  1. CrudRepository:继承Repository,实现了CRUD相关的方法
  2. PagingAndSortingRepository:继承CrudRepository,实现了分页排序相关的方法
  3. JpaRepository:继承PagingAndSortingRepositor,实现JPA规范相关的方法
4-3 查询方法定义规则和使用

Repository中查询方法定义规则和使用

</>复制代码

  1. 了解Spring Data中查询方法名称的定义规则
  2. 使用Spring Data完成复杂查询方法名称的命名

查询方法定义规则

代码演示:

1、在EmployeeRepository接口编写以下代码

</>复制代码

  1. // 使用JPA规范查询
  2. // where name like ?% and age < ?
  3. List findByNameStartingWithAndAgeLessThan(String name,Integer age);
  4. // where name like %? and age < ?
  5. List findByNameEndingWithAndAgeLessThan(String name,Integer age);
  6. // where name in (?,?...) or age < ?
  7. List findByNameInOrAgeLessThan(List name,Integer age);
  8. // where name in (?,?...) and age < ?
  9. List findByNameInAndAgeLessThan(List name,Integer age);

2、在EmployeeRepositoryTest单元测试类进行测试

</>复制代码

  1. @Test
  2. public void findByNameStartingWithAndAgeLessThanTest(){
  3. System.out.println(employeeRepository);
  4. List employees = employeeRepository.findByNameStartingWithAndAgeLessThan("test",22);
  5. if( null != employees){
  6. for (Employee employee : employees) {
  7. System.out.println(employee.toString());
  8. }
  9. }else{
  10. System.out.println("查询数据为空");
  11. }
  12. }
  13. @Test
  14. public void findByNameEndingWithAndAgeLessThanTest(){
  15. System.out.println(employeeRepository);
  16. List employees = employeeRepository.findByNameEndingWithAndAgeLessThan("6",23);
  17. if( null != employees && employees.size() > 0){
  18. for (Employee employee : employees) {
  19. System.out.println(employee.toString());
  20. }
  21. }else{
  22. System.out.println("查询数据为空");
  23. }
  24. }
  25. @Test
  26. public void findByNameInOrAgeLessThanTest(){
  27. List names = new ArrayList();
  28. names.add("test1");
  29. names.add("test2");
  30. names.add("test3");
  31. List employees = employeeRepository.findByNameInOrAgeLessThan(names,22);
  32. if( null != employees && employees.size() > 0){
  33. for (Employee employee : employees) {
  34. System.out.println(employee.toString());
  35. }
  36. }else{
  37. System.out.println("查询数据为空");
  38. }
  39. }
  40. @Test
  41. public void findByNameInAndAgeLessThanTest(){
  42. List names = new ArrayList();
  43. names.add("test1");
  44. names.add("test2");
  45. names.add("test3");
  46. List employees = employeeRepository.findByNameInAndAgeLessThan(names,22);
  47. if( null != employees && employees.size() > 0){
  48. for (Employee employee : employees) {
  49. System.out.println(employee.toString());
  50. }
  51. }else{
  52. System.out.println("查询数据为空");
  53. }
  54. }

对于按照方法命名规则来使用的话,有弊端:

</>复制代码

  1. 1)方法名比较长:约定大于配置
  2. 2)对于一些复杂的查询,是很难实现。

使用@Query注解来解决。

4-4 Query注解使用

Query注解使用

</>复制代码

  1. 在Respository方法中使用,不需要遵循查询方法命令规则
  2. 只需要将@Query定义在Respository中的方法之上即可
  3. 命名参数及索引参数的使用
  4. 本地查询

代码演示:

1、在EmployeeRepository接口编写以下代码

</>复制代码

  1. // 使用@Query注解查询
  2. /**
  3. * 自定义查询SQL
  4. * */
  5. @Query("select o from Employee o where id=(select max(id) from Employee t1)")
  6. Employee getEmployeeByMaxId();
  7. /**
  8. * 使用占位符进行参数绑定
  9. * */
  10. @Query("select o from Employee o where o.name=?1 and o.age=?2")
  11. List listEmployeeByNameAndAge(String name, Integer age);
  12. /**
  13. * 使用命名参数进行参数绑定
  14. * */
  15. @Query("select o from Employee o where o.name=:name and o.age=:age")
  16. List listEmployeeByNameAndAge2(@Param("name") String name, @Param("age")Integer age);
  17. /**
  18. * 自定义查询SQL,like,占位符进行参数绑定
  19. * */
  20. @Query("select o from Employee o where o.name like %?1%")
  21. List listEmployeeByLikeName(String name);
  22. /**
  23. * 自定义查询SQL,like,命名参数进行参数绑定
  24. * */
  25. @Query("select o from Employee o where o.name like %:name%")
  26. List listEmployeeByLikeName2(@Param("name") String name);
  27. /**
  28. * 使用原生态SQL查询
  29. * @return
  30. */
  31. @Query(nativeQuery = true,value = "select count(1) from employee")
  32. long getCount();

2、在EmployeeRepositoryTest单元测试类进行测试

</>复制代码

  1. // 使用 @Query 注解查询
  2. @Test
  3. public void getEmployeeByMaxIdTest(){
  4. Employee employee = employeeRepository.getEmployeeByMaxId();
  5. if( null != employee ){
  6. System.out.println(employee.toString());
  7. }else{
  8. System.out.println("查询数据为空");
  9. }
  10. }
  11. @Test
  12. public void listEmployeeByNameAndAgeTest(){
  13. List employees = employeeRepository.listEmployeeByNameAndAge("zhangsan",20);
  14. if( null != employees && employees.size() > 0){
  15. for (Employee employee : employees) {
  16. System.out.println(employee.toString());
  17. }
  18. }else{
  19. System.out.println("查询数据为空");
  20. }
  21. }
  22. @Test
  23. public void listEmployeeByNameAndAge2Test(){
  24. List employees = employeeRepository.listEmployeeByNameAndAge2("zhangsan",20);
  25. if( null != employees && employees.size() > 0){
  26. for (Employee employee : employees) {
  27. System.out.println(employee.toString());
  28. }
  29. }else{
  30. System.out.println("查询数据为空");
  31. }
  32. }
  33. @Test
  34. public void listEmployeeByLikeNameTest(){
  35. List employees = employeeRepository.listEmployeeByLikeName("test1");
  36. if( null != employees && employees.size() > 0){
  37. for (Employee employee : employees) {
  38. System.out.println(employee.toString());
  39. }
  40. }else{
  41. System.out.println("查询数据为空");
  42. }
  43. }
  44. @Test
  45. public void listEmployeeByLikeName2Test(){
  46. List employees = employeeRepository.listEmployeeByLikeName2("test");
  47. if( null != employees && employees.size() > 0){
  48. for (Employee employee : employees) {
  49. System.out.println(employee.toString());
  50. }
  51. }else{
  52. System.out.println("查询数据为空");
  53. }
  54. }
  55. @Test
  56. public void getCountTest(){
  57. long count = employeeRepository.getCount();
  58. System.out.println(count);
  59. }
4-5 更新操作整合事务使用

更新及删除操作整合事务的使用

</>复制代码

  1. @Modifying注解使用
  2. @Modifying结合@Query注解执行更新操作
  3. @TransactionSpring Data中的使用

事务在Spring data中的使用:

</>复制代码

  1. 1)事务一般是在Service层
  2. 2)@Query、@Modifying、@Transaction的综合使用

代码演示:

1、基于javaconfig在SpringConfig类进行事务配置

</>复制代码

  1. package com.myimooc.springdata.jpa.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.ComponentScan;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
  7. import org.springframework.jdbc.datasource.DriverManagerDataSource;
  8. import org.springframework.orm.jpa.JpaTransactionManager;
  9. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  10. import org.springframework.orm.jpa.vendor.Database;
  11. import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
  12. import org.springframework.transaction.PlatformTransactionManager;
  13. import org.springframework.transaction.annotation.EnableTransactionManagement;
  14. import java.util.Properties;
  15. /**
  16. * Spring配置类
  17. * Created by ZC on 2017/4/24.
  18. */
  19. // 声明为配置类
  20. @Configuration
  21. // 启用事务管理
  22. @EnableTransactionManagement
  23. // 启用自动扫描继承 JpaRepository 接口的类。
  24. // 注意,此注解需要配置 entityManagerFactory 和 transactionManager
  25. // 方式一:定义获取Bean方法名为 entityManagerFactory 和 transactionManager
  26. // 方式二:配置 @EnableJpaRepositories注解的 entityManagerFactoryRef 属性 为自定义获取Bean的方法名。
  27. @EnableJpaRepositories(basePackages = "com.myimooc.springdata.jpa")
  28. // 启用自动扫描 @Component 注解的Bean
  29. @ComponentScan(basePackages = "com.myimooc.springdata.jpa")
  30. public class SpringConfig{
  31. @Autowired
  32. private PropertiesConfig propertiesConfig;
  33. /**
  34. * 配置数据源
  35. * @return
  36. */
  37. @Bean
  38. public DriverManagerDataSource dataSource(){
  39. DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
  40. driverManagerDataSource.setDriverClassName(propertiesConfig.getJdbcDriverClass());
  41. driverManagerDataSource.setUrl(propertiesConfig.getJdbcUrl());
  42. driverManagerDataSource.setUsername(propertiesConfig.getJdbcUser());
  43. driverManagerDataSource.setPassword(propertiesConfig.getJdbcPassword());
  44. return driverManagerDataSource;
  45. }
  46. /**
  47. * 配置事务管理器 JpaTransactionManager
  48. * @return
  49. */
  50. @Bean(name="transactionManager")
  51. public PlatformTransactionManager transactionManager(){
  52. JpaTransactionManager transactionManager = new JpaTransactionManager();
  53. transactionManager.setDataSource(this.dataSource());
  54. transactionManager.setEntityManagerFactory(this.entityManagerFactory().getObject());
  55. return transactionManager;
  56. // return new DataSourceTransactionManager(this.dataSource());
  57. // return new JpaTransactionManager(this.entityManagerFactory().getObject());
  58. }
  59. /**
  60. * 配置JPA的 EntityManagerFactory
  61. * @return
  62. */
  63. @Bean
  64. public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
  65. LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
  66. entityManagerFactory.setDataSource(dataSource());
  67. HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
  68. jpaVendorAdapter.setGenerateDdl(true);
  69. jpaVendorAdapter.setDatabase(Database.MYSQL);
  70. entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
  71. entityManagerFactory.setPackagesToScan("com.myimooc.springdata.jpa");
  72. Properties jpaProperties = new Properties();
  73. // jpaProperties.setProperty("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy");
  74. jpaProperties.setProperty("hibernate.dialect","org.hibernate.dialect.MySQL5InnoDBDialect");
  75. jpaProperties.setProperty("hibernate.show_sql","true");
  76. jpaProperties.setProperty("hibernate.format_sql","true");
  77. jpaProperties.setProperty("hibernate.hbm2ddl.auto","update");
  78. entityManagerFactory.setJpaProperties(jpaProperties);
  79. return entityManagerFactory;
  80. }
  81. }

2、在EmployeeRepository接口编写以下代码

</>复制代码

  1. // 更新数据
  2. @Transactional
  3. @Modifying
  4. @Query("update Employee o set o.age = :age where o.id = :id")
  5. void updateAgeById(@Param("id")Integer id,@Param("age")Integer age);

3、定义Service层,实际开发中,需要定义接口,这里为了演示方便,直接使用类。

</>复制代码

  1. package com.myimooc.springdata.jpa.service;
  2. import com.myimooc.springdata.jpa.domain.Employee;
  3. import com.myimooc.springdata.jpa.repository.EmployeeCrudRepository;
  4. import com.myimooc.springdata.jpa.repository.EmployeeRepository;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import org.springframework.transaction.annotation.Transactional;
  8. import java.util.List;
  9. /**
  10. * Created by ZC on 2017/4/25.
  11. */
  12. @Service
  13. public class EmployeeService {
  14. @Autowired
  15. private EmployeeRepository employeeRepository;
  16. @Autowired
  17. private EmployeeCrudRepository employeeCrudRepository;
  18. @Transactional
  19. public void updateAgeById(Integer id, Integer age){
  20. this.employeeRepository.updateAgeById(id,age);
  21. };
  22. @Transactional
  23. public void save(List employees){
  24. this.employeeCrudRepository.save(employees);
  25. }
  26. }

4、编写EmployeeService单元测试类

</>复制代码

  1. package com.myimooc.springdata.jpa.service;
  2. import com.myimooc.springdata.jpa.config.SpringConfig;
  3. import com.myimooc.springdata.jpa.repository.EmployeeRepository;
  4. import org.junit.After;
  5. import org.junit.Assert;
  6. import org.junit.Before;
  7. import org.junit.Test;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  10. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  11. import org.springframework.transaction.PlatformTransactionManager;
  12. /**
  13. * EmployeeService单元测试类
  14. * Created by ZC on 2017/4/25.
  15. */
  16. public class EmployeeServiceTest {
  17. private ApplicationContext ctx = null;
  18. private EmployeeService employeeService = null;
  19. @Before
  20. public void init(){
  21. ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  22. employeeService = ctx.getBean(EmployeeService.class);
  23. }
  24. @After
  25. public void destroy(){
  26. ctx = null;
  27. }
  28. @Test
  29. public void transactionManagerTest(){
  30. PlatformTransactionManager transactionManager = (PlatformTransactionManager)ctx.getBean(PlatformTransactionManager.class);
  31. Assert.assertNotNull(transactionManager);
  32. }
  33. // 更新操作
  34. @Test
  35. public void updateAgeByIdTest(){
  36. employeeService.updateAgeById(1,55);
  37. }
  38. }
第五章:Spring Data JPA高级 5-1 CrudRepository接口使用详解

CrudRepository接口使用详解

</>复制代码

  1. save(entity):保存一个实体
  2. save(entities):保存多个实体
  3. findOne(id):找到一个对象
  4. exists(id):根据ID判断对象是否存在
  5. findAll():找到所有实体对象
  6. delete(id):根据ID删除实体对象
  7. delete(entity):根据实体对象删除实体对象
  8. delete(entities):删除多个实体对象
  9. deleteAll():删除所有实体对象

代码演示:

1、编写EmployeeCrudRepository接口

</>复制代码

  1. package com.myimooc.springdata.jpa.repository;
  2. import com.myimooc.springdata.jpa.domain.Employee;
  3. import org.springframework.data.repository.CrudRepository;
  4. /**
  5. * 使用 CrudRepository 接口
  6. * Created by ZC on 2017/4/26.
  7. */
  8. public interface EmployeeCrudRepository extends CrudRepository{
  9. }

2、编写EmployeeCrudRepositoryTest单元测试类

</>复制代码

  1. package com.myimooc.springdata.jpa.repository;
  2. import com.myimooc.springdata.jpa.config.SpringConfig;
  3. import com.myimooc.springdata.jpa.domain.Employee;
  4. import org.junit.After;
  5. import org.junit.Before;
  6. import org.junit.Test;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. /**
  12. * EmployeeRepository单元测试类
  13. * Created by ZC on 2017/4/24.
  14. */
  15. public class EmployeeCrudRepositoryTest {
  16. private ApplicationContext ctx = null;
  17. private EmployeeCrudRepository employeeCrudRepository = null;
  18. @Before
  19. public void init(){
  20. ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  21. employeeCrudRepository = ctx.getBean(EmployeeCrudRepository.class);
  22. }
  23. @After
  24. public void destroy(){
  25. ctx = null;
  26. }
  27. @Test
  28. public void saveTest(){
  29. List employees = new ArrayList();
  30. Employee employee = null;
  31. for(int i=0;i<100;i++){
  32. employee = new Employee();
  33. employee.setName("test"+i);
  34. employee.setAge(100 - i);
  35. employees.add(employee);
  36. }
  37. employeeCrudRepository.save(employees);
  38. }
  39. }
5-2 PagingAndSortingRespository接口使用详解

PagingAndSortingRespository接口使用详解

</>复制代码

  1. 该接口包含分页和排序的功能
  2. 带排序的查询:findAll(Sort sort)
  3. 带排序的分页查询:findAll(Pageable pageable)

代码演示:

1、编写EmployeePagingAndSortingRepository接口

</>复制代码

  1. package com.myimooc.springdata.jpa.repository;
  2. import com.myimooc.springdata.jpa.domain.Employee;
  3. import org.springframework.data.repository.PagingAndSortingRepository;
  4. /**
  5. * 使用 PagingAndSortingRepository 实现分页和排序功能
  6. * Created by ZC on 2017/4/26.
  7. */
  8. public interface EmployeePagingAndSortingRepository extends PagingAndSortingRepository {
  9. }

2、编写EmployeePagingAndSortingRepositoryTest单元测试类

</>复制代码

  1. package com.myimooc.springdata.jpa.repository;
  2. import com.myimooc.springdata.jpa.config.SpringConfig;
  3. import com.myimooc.springdata.jpa.domain.Employee;
  4. import com.myimooc.springdata.jpa.repository.EmployeePagingAndSortingRepository;
  5. import com.myimooc.springdata.jpa.service.EmployeeService;
  6. import org.junit.After;
  7. import org.junit.Assert;
  8. import org.junit.Before;
  9. import org.junit.Test;
  10. import org.springframework.context.ApplicationContext;
  11. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  12. import org.springframework.data.domain.Page;
  13. import org.springframework.data.domain.PageRequest;
  14. import org.springframework.data.domain.Pageable;
  15. import org.springframework.data.domain.Sort;
  16. import org.springframework.data.repository.PagingAndSortingRepository;
  17. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. /**
  21. * PagingAndSortingRepository 单元测试类
  22. * Created by ZC on 2017/4/26.
  23. */
  24. public class EmployeePagingAndSortingRepositoryTest {
  25. private ApplicationContext ctx = null;
  26. private EmployeePagingAndSortingRepository employeePagingAndSortingRepository = null;
  27. @Before
  28. public void init(){
  29. ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  30. employeePagingAndSortingRepository = ctx.getBean(EmployeePagingAndSortingRepository.class);
  31. }
  32. @After
  33. public void destroy(){
  34. ctx = null;
  35. }
  36. /**
  37. * 分页功能测试
  38. */
  39. @Test
  40. public void pageTest(){
  41. // page: index是从0开始的,不是从1开始的
  42. Pageable pageable = new PageRequest(0,9);
  43. Page employeePage = employeePagingAndSortingRepository.findAll(pageable);
  44. System.out.println("查询的总页数:"+employeePage.getTotalPages());
  45. System.out.println("查询的总记录数:"+employeePage.getTotalElements());
  46. System.out.println("查询的当前第几页:"+(employeePage.getNumber() + 1));
  47. System.out.println("查询的当前页面的集合:"+employeePage.getContent());
  48. System.out.println("查询的当前页面的记录数:"+employeePage.getNumberOfElements());
  49. }
  50. /**
  51. * 分页和排序功能测试
  52. */
  53. @Test
  54. public void pageAndSort(){
  55. Sort.Order order = new Sort.Order(Sort.Direction.ASC,"id");
  56. Sort sort = new Sort(order);
  57. // page: index是从0开始的,不是从1开始的
  58. Pageable pageable = new PageRequest(0,5,sort);
  59. Page employeePage = employeePagingAndSortingRepository.findAll(pageable);
  60. System.out.println("查询的总页数:"+employeePage.getTotalPages());
  61. System.out.println("查询的总记录数:"+employeePage.getTotalElements());
  62. System.out.println("查询的当前第几页:"+(employeePage.getNumber() + 1));
  63. System.out.println("查询的当前页面的集合:"+employeePage.getContent());
  64. System.out.println("查询的当前页面的记录数:"+employeePage.getNumberOfElements());
  65. }
  66. }
5-3 JpaRepository接口使用详解

JpaRepository接口使用详解

</>复制代码

  1. finaAll:查询所有记录
  2. findAll(Sort sort):查询所有记录并排序
  3. save(entities):保存多个实体对象
  4. fiush:
  5. deleteInBatch(entities):一个批次里面删除那些实体

代码演示:

1、编写EmployeeJpaRepository接口

</>复制代码

  1. package com.myimooc.springdata.jpa.repository;
  2. import com.myimooc.springdata.jpa.domain.Employee;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.repository.PagingAndSortingRepository;
  5. /**
  6. * 使用 JpaRepository 接口
  7. * Created by ZC on 2017/4/26.
  8. */
  9. public interface EmployeeJpaRepository extends JpaRepository {
  10. }

2、编写EmployeeJpaRepositoryTest单元测试类

</>复制代码

  1. package com.myimooc.springdata.jpa.repository;
  2. import com.myimooc.springdata.jpa.config.SpringConfig;
  3. import com.myimooc.springdata.jpa.domain.Employee;
  4. import com.myimooc.springdata.jpa.repository.EmployeeJpaRepository;
  5. import org.junit.After;
  6. import org.junit.Before;
  7. import org.junit.Test;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  10. import org.springframework.data.domain.Page;
  11. import org.springframework.data.domain.PageRequest;
  12. import org.springframework.data.domain.Pageable;
  13. import org.springframework.data.domain.Sort;
  14. import org.springframework.data.jpa.repository.JpaRepository;
  15. import org.springframework.data.repository.PagingAndSortingRepository;
  16. /**
  17. * EmployeeJpaRepository 单元测试类
  18. * Created by ZC on 2017/4/26.
  19. */
  20. public class EmployeeJpaRepositoryTest {
  21. private ApplicationContext ctx = null;
  22. private EmployeeJpaRepository employeeJpaRepository = null;
  23. @Before
  24. public void init(){
  25. ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  26. employeeJpaRepository = ctx.getBean(EmployeeJpaRepository.class);
  27. }
  28. @After
  29. public void destroy(){
  30. ctx = null;
  31. }
  32. @Test
  33. public void findTest(){
  34. Employee employee = employeeJpaRepository.findOne(99);
  35. System.out.println("employee"+employee.toString());
  36. System.out.println("employee(10)"+employeeJpaRepository.exists(10));
  37. System.out.println("employee(102)"+employeeJpaRepository.exists(102));
  38. }
  39. }
5-4 JpaSpecificationExecutor接口使用详解

JpaSpecificationExecutor接口使用详解

</>复制代码

  1. Specification封装了JPA Criteria查询条件

代码演示:

1、编写EmployeeJpaSpecificationExecutor接口

</>复制代码

  1. package com.myimooc.springdata.jpa.repository;
  2. import com.myimooc.springdata.jpa.domain.Employee;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  5. /**
  6. * 使用 JpaSpecificationExecutor 接口
  7. * Created by ZC on 2017/4/26.
  8. */
  9. public interface EmployeeJpaSpecificationExecutor extends JpaRepository ,
  10. JpaSpecificationExecutor{
  11. }

2、编写EmployeeJpaSpecificationExecutorTest单元测试类

</>复制代码

  1. package com.myimooc.springdata.jpa.repository;
  2. import com.myimooc.springdata.jpa.config.SpringConfig;
  3. import com.myimooc.springdata.jpa.domain.Employee;
  4. import org.junit.After;
  5. import org.junit.Before;
  6. import org.junit.Test;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  9. import org.springframework.data.domain.Page;
  10. import org.springframework.data.domain.PageRequest;
  11. import org.springframework.data.domain.Pageable;
  12. import org.springframework.data.domain.Sort;
  13. import org.springframework.data.jpa.domain.Specification;
  14. import javax.persistence.criteria.*;
  15. /**
  16. * EmployeeJpaSpecificationExecutor 单元测试类
  17. * Created by ZC on 2017/4/26.
  18. */
  19. public class EmployeeJpaSpecificationExecutorTest {
  20. private ApplicationContext ctx = null;
  21. private EmployeeJpaSpecificationExecutor employeeJpaSpecificationExecutor = null;
  22. @Before
  23. public void init(){
  24. ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  25. employeeJpaSpecificationExecutor = ctx.getBean(EmployeeJpaSpecificationExecutor.class);
  26. }
  27. @After
  28. public void destroy(){
  29. ctx = null;
  30. }
  31. /**
  32. * 1、分页
  33. * 2、排序
  34. * 3、查询条件:age > 50
  35. */
  36. @Test
  37. public void queryTest(){
  38. Sort.Order order = new Sort.Order(Sort.Direction.DESC,"id");
  39. Sort sort = new Sort(order);
  40. // page: index是从0开始的,不是从1开始的
  41. Pageable pageable = new PageRequest(0,5,sort);
  42. /**
  43. * root : 就是我们要查询的类型 (Employee)
  44. * query : 添加查询条件
  45. * cb : 构建 Predicate
  46. */
  47. Specification specification = new Specification() {
  48. // 查询条件
  49. public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
  50. // root (employee (age))
  51. Path path = root.get("age");
  52. return cb.gt(path,50);
  53. }
  54. };
  55. Page employeePage = employeeJpaSpecificationExecutor.findAll(specification,pageable);
  56. System.out.println("查询的总页数:"+employeePage.getTotalPages());
  57. System.out.println("查询的总记录数:"+employeePage.getTotalElements());
  58. System.out.println("查询的当前第几页:"+(employeePage.getNumber() + 1));
  59. System.out.println("查询的当前页面的集合:"+employeePage.getContent());
  60. System.out.println("查询的当前页面的记录数:"+employeePage.getNumberOfElements());
  61. }
  62. }
第六章:课程总结 6-4 课程总结

课程总结

</>复制代码

  1. Spring Data概览
  2. 传统方式访问数据库
  3. Spring Data快速起步
  4. Spring Data JPA进阶
  5. Spring Data JAP高级

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69926.html

相关文章

  • 课网_《SpringMVC起步》学习总结

    摘要:起步学习总结时间年月日星期四说明本文部分内容均来自慕课网。慕课网教学示例源码个人学习源码第一章简介起步课程简介简介基本概念项目搭建用进行开发课程总结前端控制器开发应用的通用架构方式。 《SpringMVC起步》学习总结 时间:2017年2月16日星期四说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学示例源码:https://github.com/z...

    zombieda 评论0 收藏0
  • 课网_《SpringMVC拦截器》学习总结

    摘要:拦截器学习总结时间年月日星期六说明本文部分内容均来自慕课网。慕课网教学示例源码暂无。拦截器不依赖与容器,过滤器依赖与容器。拦截器只能对请求起作用,而过滤器则可以对几乎所有的请求起作用。共性问题在拦截器中处理,可以减少重复代码,便于维护。 《SpringMVC拦截器》学习总结 时间:2017年2月18日星期六说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.co...

    calx 评论0 收藏0
  • 课网_《2小时学会SpringBoot》学习总结

    摘要:小时学会学习总结时间年月日星期六说明本文部分内容均来自慕课网。慕课网教学示例源码暂无。数据库操作下第六章事务管理事务管理只有查询的时候不加事务,其它任何操作都要加事务。第七章课程回顾课程回顾总结介绍安装配置的使用数据库操作 《2小时学会SpringBoot》学习总结 时间:2017年2月18日星期六说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学示...

    aisuhua 评论0 收藏0
  • 课网_《Spring事务管理》学习总结

    摘要:事务管理学习总结时间年月日星期二说明本文部分内容均来自慕课网。一致性一致性指事务前后数据的完整性必须保持一致。声明式事务管理基于的方式很少使用需要为每个进行事务管理的类,配置一个进行增强。 《Spring事务管理》学习总结 时间:2017年2月7日星期二说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com/教学示例源码:https://github.com...

    Airy 评论0 收藏0

发表评论

0条评论

skinner

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<