springdata基础

转载博文:https://blog.****.net/cs_hnu_scw/article/details/80720206

情景引入:

小白:快起床快起床,起来学习起来学习~~~~

我:你能不能让我安心点,今天周末,咱们不学习,放假放假!(适当的休息还是很有用的哦,劳逸结合~!)

小白:不行,昨天不是才休息的吗?我遇到问题遇到问题了~~

我:快说,你又有什么问题?你是十万个为什么吗?

小白:我学习完你上次对我说的关于通用Mapper的内容了,并且确实相比我之前的开发编码快很多,但是,但是,我现在有个想法,我想进一步的进行优化。

我:很不错,看样子,你是有认真学习我给你讲的内容嘛。通用Mapper的配置确实是很有用的,也是用的比较多的方式之一。

小白:你看,像我原来使用过Hibernate,我觉得这样的ORM架构就非常好,它内置很多的数据层操作的API,那么有没有什么更好的方法,可以类似这样,而不需要编写mapper.xml文件的呢?感觉好麻烦。。。。。

我:这个嘛。。你的意思是说,想直接利用接口就进行数据层操作是吗?就类似通用Mapper这样的形式是么?

小白:对的对的,你真聪明。。。

我:emmmmmmm,那看在你夸我的面子上,我就教你一个新知识吧。这就是Spring Data!!!!

情景分析:

        在JavaWeb开发中,不管你用什么框架,开发的什么功能项目。都存在着对于数据库的数据交互。我们可能会针对某些烦人的操作感到无聊,总想有什么好的方式进行项目的开发。是的,这确实就是我们工作中遇到的实际存在的问题。一个好的架构,对于我们编程人员来说就是一种福音,那么,我就用这篇博文来讲一种数据库交互的方式---------Spring Data!

博文目录:

一:Spring Data简介

二:传统方式的数据库访问方式-----JDBC

三:基于Spring框架数据库访问方式---------JdbcTemplate模板

四:Spring Data的入门

五:Spring Data的进阶

六:让我给你总结总结

温馨提示:本博文的环境都是基于:IDEA+windows7+Mysql 5.7

简介

    Spring Data的使命是为数据访问提供熟悉且一致的基于Spring的编程模型,同时仍保留底层数据存储的特殊特性。
    它使得使用数据访问技术,关系数据库和非关系数据库,map-reduce框架以及基于云的数据服务变得很容易。 这是一个总括项目,其中包含许多特定于特定数据库的子项目。 这些项目是通过与许多支持这些令人兴奋的技术的公司和开发人员合作开发的。                                                                                                                                        -------Spring Data官网翻译

        另外,用通俗的话来说:在企业级JavaEE应用开发中,对数据库的访问和操作是必须的。Spring Data作为SpringSource的其中一个子项目,旨在统一和简化对各类型持久化存储和访问,而不拘泥于是关系型数据库还是NoSQL数据存储,使得对数据库的访问变得方便快捷,并支持MapReduce框架及云计算服务;对于拥有海量数据的项目,可以用Spring Data来简化项目的开发,就如Spring Framework对JDBC、ORM的支持一样,Spring Data会让数据的访问变得更加方便,极大提高开发效率。

传统的数据库访问方式

    当我们在学习JavaWeb的初级阶段的时候,我想,大家肯定学习过一种与数据库进行交互的方式,那就是-----JDBC。是的,它是最原始的一种方式,然而,它却有着很多的不足之处。
   或许,你已经忘记了JDBC是如何操作数据库的了,没关系,我就用个简单的例子,来帮助大家进行回顾。这样对于我们后续的学习还是很有帮助的。

(一)让我们来搭一搭JDBC的开发实例(IDEA编辑器+Maven+mysql)

步骤:

1:使用IDEA编辑器创建一个Maven项目,不明白的欢迎看我Maven知识点的博文

springdata基础

2:在pom.xml文件中添加下面的依赖(顺便配置一下下载依赖的仓库---基于之前没有配置过的朋友)

  1. <!-- 配置阿里云仓库,要不然从*maven库下载很慢-->
  2. <repositories>
  3. <repository>
  4. <id>nexus-aliyun</id>
  5. <name>nexus-aliyun</name>
  6. <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
  7. <releases>
  8. <enabled>true</enabled>
  9. </releases>
  10. <snapshots>
  11. <enabled>false</enabled>
  12. </snapshots>
  13. </repository>
  14. </repositories>
  15. <!-- mysql -->
  16. <dependency>
  17. <groupId>mysql</groupId>
  18. <artifactId>mysql-connector-java</artifactId>
  19. <version>5.1.38</version>
  20. </dependency>

3:新建一个文件夹resource(和java目录同级,并且创建之后记得将这个文件右击然后选择Mark Dirctory as 然后选择resource即可),用于存储相关的配置文件,这里主要是放置jdbc.properties,便于灵活性的修改数据库连接等内容。

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

4:创建JDBC获取连接和释放资源的工具类(这个还是比较有用的,方便后续操作)

  1. package com.hnu.scw.utils;
  2. import javax.xml.transform.Result;
  3. import java.io.InputStream;
  4. import java.sql.*;
  5. import java.util.Properties;
  6. /**
  7. * @ Author :scw
  8. * @ Date :Created in 下午 8:48 2018/6/21 0021
  9. * @ Description:JDBC相关的工具类
  10. * @ Modified By:
  11. * @Version: $version$
  12. */
  13. public class JDBCUtil {
  14. /**
  15. * 根据properties获取数据库连接
  16. * @return
  17. * @throws Exception
  18. */
  19. public static Connection getConnection() throws Exception {
  20. InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
  21. Properties properties = new Properties();
  22. properties.load(resourceAsStream);
  23. String url = properties.getProperty("jdbc.url");
  24. String userName = properties.getProperty("jdbc.username");
  25. String password = properties.getProperty("jdbc.password");
  26. String dirverClass = properties.getProperty("jdbc.driverClass");
  27. Class.forName(dirverClass);
  28. Connection connection = DriverManager.getConnection(url, userName, password);
  29. return connection;
  30. }
  31. /**
  32. * 释放数据库连接的相关对象
  33. * @param resultSet
  34. * @param statement
  35. * @param connection
  36. */
  37. public static void release(ResultSet resultSet , Statement statement , Connection connection){
  38. if(resultSet != null){
  39. try {
  40. resultSet.close();
  41. } catch (SQLException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. if(statement != null){
  46. try {
  47. statement.close();
  48. } catch (SQLException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. if(connection != null){
  53. try {
  54. connection.close();
  55. } catch (SQLException e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. }
  60. }

5:在数据库中创建一个数据表,并且同时创建一个实体类(以student学生实体为例子)

表结构如下:

springdata基础

  1. package com.hnu.scw.model;
  2. /**
  3. * @ Author :scw
  4. * @ Date :Created in 下午 5:14 2018/6/22 0022
  5. * @ Description:定义一个实体对象
  6. * @ Modified By:
  7. * @Version: $version$
  8. */
  9. public class Student {
  10. private Integer id;
  11. private String name;
  12. private Integer age ;
  13. public Integer getId() {
  14. return id;
  15. }
  16. public void setId(Integer id) {
  17. this.id = id;
  18. }
  19. public String getName() {
  20. return name;
  21. }
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25. public Integer getAge() {
  26. return age;
  27. }
  28. public void setAge(Integer age) {
  29. this.age = age;
  30. }
  31. @Override
  32. public String toString() {
  33. return "Student{" +
  34. "id=" + id +
  35. ", name='" + name + '\'' +
  36. ", age=" + age +
  37. '}';
  38. }
  39. }

6:编写Dao层操作数据库接口方法

  1. package com.hnu.scw.dao;
  2. import com.hnu.scw.model.Student;
  3. import java.util.List;
  4. /**
  5. * @ Author :scw
  6. * @ Date :Created in 下午 5:16 2018/6/22 0022
  7. * @ Description:定义操作student的dao接口层
  8. * @ Modified By:
  9. * @Version: $version$
  10. */
  11. public interface StudentDao {
  12. /**
  13. * 查询所有的学生信息
  14. * @return
  15. */
  16. List<Student> selectAllStudent();
  17. }

7:编写Dao层接口的实现类

  1. package com.hnu.scw.dao.impl;
  2. import com.hnu.scw.dao.StudentDao;
  3. import com.hnu.scw.model.Student;
  4. import com.hnu.scw.utils.JDBCUtil;
  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. * @ Author :scw
  12. * @ Date :Created in 下午 5:22 2018/6/22 0022
  13. * @ Description:${description}
  14. * @ Modified By:
  15. * @Version: $version$
  16. */
  17. public class StudentDaoImpl implements StudentDao {
  18. @Override
  19. public List<Student> selectAllStudent() {
  20. Connection connection = null;
  21. PreparedStatement statement = null;
  22. ResultSet resultSet = null;
  23. ArrayList<Student> students = new ArrayList<>();
  24. try {
  25. String sql = "select * from Student ";
  26. connection = JDBCUtil.getConnection();
  27. statement = connection.prepareStatement(sql);
  28. resultSet = statement.executeQuery();
  29. Student student = null ;
  30. while(resultSet.next()){
  31. int id = resultSet.getInt("id");
  32. String name = resultSet.getString("name");
  33. int age = resultSet.getInt("age");
  34. student = new Student();
  35. student.setId(id);
  36. student.setName(name);
  37. student.setAge(age);
  38. students.add(student);
  39. }
  40. }catch (Exception e){
  41. e.printStackTrace();
  42. }finally {
  43. JDBCUtil.release(resultSet,statement , connection);
  44. }
  45. return students;
  46. }
  47. }

8:进行jdbc方法的测试。编写单元测试类

  1. package com.hnu.scw;
  2. import static org.junit.Assert.assertTrue;
  3. import com.hnu.scw.dao.StudentDao;
  4. import com.hnu.scw.dao.impl.StudentDaoImpl;
  5. import com.hnu.scw.model.Student;
  6. import com.hnu.scw.utils.JDBCUtil;
  7. import org.junit.Test;
  8. import java.sql.Connection;
  9. import java.util.List;
  10. /**
  11. * Unit test for simple App.
  12. */
  13. public class JDBCTest {
  14. /**
  15. * 测试jdbc连接是否成功
  16. * @throws Exception
  17. */
  18. @Test
  19. public void testConnection() throws Exception {
  20. JDBCUtil.getConnection();
  21. }
  22. /**
  23. * 测试jdbc操作数据库方法(查询所有的学生表信息)
  24. */
  25. @Test
  26. public void testQuerySQL(){
  27. StudentDao studentDao = new StudentDaoImpl();
  28. List<Student> students = studentDao.selectAllStudent();
  29. for (Student s : students) {
  30. System.out.println(s.toString());
  31. }
  32. }
  33. }

温馨提示:当执行了方法之后,如果提示单元测试成功,并打印我们预期的内容的话,那就说明我们的流程是成功的了哦!

JDBC操作的总结:

(1)首先,我们发现代码很冗余,因为对于数据库的连接的资源都需要我们进行手动的释放

(2)数据库操作的代码重复性过多,在我们的实例中,我们仅仅写了一个查询所有数据的方法就有那么多的代码,而如果我们还有其他的数据库,比如增删改查,那么可想而知,代码有多少的重复。

既然,JDBC有这么多的问题,那我们肯定就要想一个解决的办法,那么继续,别停下,看下面的内容:

基于Spring框架的JDBCTemplate模板方法

       同理,这个方式,我想大家在初学Spring的时候都有接触过,可能在实际项目中不会用这样的方式,毕竟有很多的数据库操作框架,比如Mybatis和Hibernate。但是,这也是一种方式的改进,所以,我觉得还是有必要进行说明一下的。

(一)让我们搭建一下JdbcTemplate模板方法(IDEA编辑器+Spring +Maven+mysql,直接基于上面的环境就可以)

步骤:

1:在pom.xml文件中添加spring的相关依赖

  1. <!-- spring-jdbc 为了获取jdbtTemplete的处理-->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-jdbc</artifactId>
  5. <version>4.3.5.RELEASE</version>
  6. </dependency>
  7. <!-- spring 为了进行spring的配置-->
  8. <dependency>
  9. <groupId>org.springframework</groupId>
  10. <artifactId>spring-context</artifactId>
  11. <version>4.3.5.RELEASE</version>
  12. </dependency>

2:编写Spring的相关配置(这里命名为applicationcontext.xml),文件放在之前创建的resource目录即可

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation = "http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  7. <property name="url" value="jdbc:mysql:///springdata" />
  8. <property name="username" value="root" />
  9. <property name="password" value="123456" />
  10. <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  11. </bean>
  12. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  13. <property name="dataSource" ref="dataSource"/>
  14. </bean>
  15. <!--让操作数据库的对象由spring进行管理-->
  16. <bean id="jdbcTemplateStudentDaoImpl" class="com.hnu.scw.spring.jdbctemplate.dao.impl.JDBCTemplateStudentDaoImpl">
  17. <property name="jdbcTemplate" ref="jdbcTemplate" />
  18. </bean>
  19. </beans>

3:编写Dao层接口代码

  1. package com.hnu.scw.spring.jdbctemplate.dao;
  2. import com.hnu.scw.model.Student;
  3. import java.util.List;
  4. /**
  5. * @ Author :scw
  6. * @ Date :Created in 下午 7:56 2018/6/22 0022
  7. * @ Description:基于jdbctemplate的模板方法的dao接口
  8. * @ Modified By:
  9. * @Version: $version$
  10. */
  11. public interface JDBCTemplateStudentDao {
  12. /**
  13. * 查询所有的学生数据
  14. * @return
  15. */
  16. List<Student> selectAllStudent();
  17. }

4:编写Dao层实体类代码

  1. package com.hnu.scw.spring.jdbctemplate.dao.impl;
  2. import com.hnu.scw.model.Student;
  3. import com.hnu.scw.spring.jdbctemplate.dao.JDBCTemplateStudentDao;
  4. import org.springframework.jdbc.core.JdbcTemplate;
  5. import org.springframework.jdbc.core.RowCallbackHandler;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. /**
  11. * @ Author :scw
  12. * @ Date :Created in 下午 7:50 2018/6/22 0022
  13. * @ Description:测试jdbctemplate进行操作数据库
  14. * @ Modified By:
  15. * @Version: $version$
  16. */
  17. public class JDBCTemplateStudentDaoImpl implements JDBCTemplateStudentDao{
  18. private JdbcTemplate jdbcTemplate ;
  19. public JdbcTemplate getJdbcTemplate() {
  20. return jdbcTemplate;
  21. }
  22. //注入JdbcTemplate
  23. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  24. this.jdbcTemplate = jdbcTemplate;
  25. }
  26. /**
  27. * 进行jdbctemplate模板来操作数据库
  28. * @return
  29. */
  30. @Override
  31. public List<Student> selectAllStudent() {
  32. final ArrayList<Student> students = new ArrayList<>();
  33. String sql = "select * from student";
  34. jdbcTemplate.query(sql, new RowCallbackHandler() {
  35. @Override
  36. public void processRow(ResultSet resultSet) throws SQLException {
  37. int id = resultSet.getInt("id");
  38. String name = resultSet.getString("name");
  39. int age = resultSet.getInt("id");
  40. Student student = new Student();
  41. student.setAge(age);
  42. student.setName(name);
  43. student.setId(id);
  44. students.add(student);
  45. }
  46. });
  47. return students;
  48. }
  49. }

5:编写单元测试方法。

  1. package com.hnu.scw;
  2. import com.hnu.scw.model.Student;
  3. import com.hnu.scw.spring.jdbctemplate.dao.JDBCTemplateStudentDao;
  4. import com.hnu.scw.spring.jdbctemplate.dao.impl.JDBCTemplateStudentDaoImpl;
  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.support.ClassPathXmlApplicationContext;
  10. import org.springframework.jdbc.core.JdbcTemplate;
  11. import javax.sql.DataSource;
  12. import java.util.List;
  13. /**
  14. * @ Author :scw
  15. * @ Date :Created in 下午 7:37 2018/6/22 0022
  16. * @ Description:关于Spring中jdbctemplete的相关测试
  17. * @ Modified By:
  18. * @Version: $version$
  19. */
  20. public class SpringJDBCTempleteTest {
  21. private ApplicationContext context = null;
  22. private JDBCTemplateStudentDao jdbcTemplateStudentDao ;
  23. /**
  24. * 在进行测试单元之前进行的操作(这里主要就是注入bean)
  25. */
  26. @Before
  27. public void setContextTool(){
  28. System.out.println("提前注入context");
  29. context = new ClassPathXmlApplicationContext("applicationContext.xml");
  30. jdbcTemplateStudentDao = (JDBCTemplateStudentDao) context.getBean("jdbcTemplateStudentDaoImpl");
  31. }
  32. /**
  33. * 测试注入DataSource
  34. */
  35. @Test
  36. public void testDataSource(){
  37. DataSource dataSource = (DataSource) context.getBean("dataSource");
  38. //通过断言进行判断
  39. Assert.assertNotNull(dataSource);
  40. }
  41. /**
  42. * 测试jdbcTemplate注入是否成功
  43. */
  44. @Test
  45. public void testJDBCTemplate(){
  46. JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
  47. //通过断言进行判断
  48. Assert.assertNotNull(jdbcTemplate);
  49. }
  50. /**
  51. * 测试通过jdbctemplate进行的数据库操作
  52. */
  53. @Test
  54. public void testJdbcTemplateStudentDaoImpl(){
  55. List<Student> students = jdbcTemplateStudentDao.selectAllStudent();
  56. for (Student s : students) {
  57. System.out.println(s.toString());
  58. }
  59. }
  60. }

温馨提示:如果执行了上面的几个单元测试后,都是绿色,那就说明我们的环境都是正确的哦。!(单元测试要一个个来,这样在我们的项目开发中是非常有必要的,这样可以方便我们找到错误最早 出现的位置,而别写了很多代码之后,才进行一次性的测试,这是非常不好的习惯!)

JdbcTemplate操作数据库的总结

(1)通过spring我们可以方便对于对象的管理,这里就是jdbcTemplate对象

(2)但是,还是存在一个很多的问题,就是操作过于麻烦,想想,我们上面就是简单的操作一个查询,就需要编写这样的代码,而我们项目中还有其他的方法,这想想就很可怕了吧。

OK,这个方式还是没有解决我们的问题,那么接下来,Spring Data闪亮登场!!!!

Spring Data的入门

    经过前两种方式的编写,我们都发现了很多的问题。而为什么我要这样写,就是让大家有一种慢慢熟悉的感觉,这样才会觉得Spring Data的方便之处,对于其的内容就更加的有兴趣。

(一)让我们来搭建Spring Data的开发环境(还是和上面一样哦!)

步骤:

1:在pom,xml文件中添加Spring Data的相关依赖

  1. <!-- spring-data-jpa -->
  2. <dependency>
  3. <groupId>org.springframework.data</groupId>
  4. <artifactId>spring-data-jpa</artifactId>
  5. <version>1.8.0.RELEASE</version>
  6. </dependency>
  7. <!-- 配置hibernate的实体管理依赖-->
  8. <dependency>
  9. <groupId>org.hibernate</groupId>
  10. <artifactId>hibernate-entitymanager</artifactId>
  11. <version>4.3.6.Final</version>
  12. </dependency>

2:编写JavaBean实体。(我这里就不用上面的student,而用一个新的teacher来演示,便于大家进行查看,而且我们不需要提前在数据库中创建表哦,当我们没有的时候,这个是会自动创建表的呢!方便不?

  1. package com.hnu.scw.model;
  2. import javax.persistence.Column;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.Id;
  6. /**
  7. * @ Author :scw
  8. * @ Date :Created in 下午 8:37 2018/6/22 0022
  9. * @ Description:编写一个老师实体类
  10. * @ Modified By:
  11. * @Version: $version$
  12. */
  13. @Entity
  14. public class Teacher {
  15. //配置表的id,并且是使用自增
  16. @Id
  17. @GeneratedValue
  18. private Integer id;
  19. //设置列的长度为15,并且不能为空
  20. @Column(length = 15 ,nullable = false)
  21. private String name ;
  22. private String classNumber ;
  23. public Integer getId() {
  24. return id;
  25. }
  26. public void setId(Integer id) {
  27. this.id = id;
  28. }
  29. public String getName() {
  30. return name;
  31. }
  32. public void setName(String name) {
  33. this.name = name;
  34. }
  35. public String getClassNumber() {
  36. return classNumber;
  37. }
  38. public void setClassNumber(String classNumber) {
  39. this.classNumber = classNumber;
  40. }
  41. @Override
  42. public String toString() {
  43. return "Teacher{" +
  44. "id=" + id +
  45. ", name='" + name + '\'' +
  46. ", classNumber='" + classNumber + '\'' +
  47. '}';
  48. }
  49. }

表结构如下:

springdata基础

3:编写Spring 和Spring Data的相关配置文件(我命名为springdatacontext.xml),放在resource文件目录下。

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/data/jpa
  9. http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  10. <!--配置数据源-->
  11. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  12. <property name="url" value="jdbc:mysql:///springdata" />
  13. <property name="username" value="root" />
  14. <property name="password" value="123456" />
  15. <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  16. </bean>
  17. <!--配置entityManagerFactory 用于管理实体的一些配置-->
  18. <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  19. <property name="dataSource" ref="dataSource" />
  20. <property name="jpaVendorAdapter">
  21. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
  22. </property>
  23. <property name="packagesToScan" value="com.hnu.scw"/>
  24. <property name="jpaProperties">
  25. <props>
  26. <prop key="hibernate.ejb.naming_strategy" >org.hibernate.cfg.ImprovedNamingStrategy</prop>
  27. <prop key="hibernate.dialect" >org.hibernate.dialect.MySQL5InnoDBDialect</prop>
  28. <prop key="hibernate.show_sql" >true</prop>
  29. <prop key="hibernate.format_sql" >true</prop>
  30. <!--配置是否实体自动生成数据表-->
  31. <prop key="hibernate.hbm2ddl.auto" >update</prop>
  32. </props>
  33. </property>
  34. </bean>
  35. <!--配置事务管理器-->
  36. <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  37. <property name="entityManagerFactory" ref="entityManagerFactory"/>
  38. </bean>
  39. <!--配置支持事务注解-->
  40. <tx:annotation-driven transaction-manager="transactionManager"/>
  41. <!--配置spring data-->
  42. <jpa:repositories base-package="com.hnu.scw" entity-manager-factory-ref="entityManagerFactory"/>
  43. <!--配置spring的扫描包-->
  44. <context:component-scan base-package="com.hnu.scw"/>
  45. </beans>

进入我们真正的使用了哦!!!!!!重点来了~~~~~

4:编写我们需要进行操作实体的Dao层接口-------------------重点,,好好看这接口的内容!

  1. package com.hnu.scw.repository;
  2. import com.hnu.scw.model.Teacher;
  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.RepositoryDefinition;
  7. import org.springframework.data.repository.query.Param;
  8. import java.util.List;
  9. /**
  10. * @ Author :scw
  11. * @ Date :Created in 下午 9:17 2018/6/22 0022
  12. * @ Description:基于Spring Data接口的dao层开发接口
  13. * @ Modified By:
  14. * @Version: $version$
  15. */
  16. //有两种方式,要么用注解要么用继承
  17. //@RepositoryDefinition(domainClass = Teacher.class ,idClass = Integer.class)
  18. public interface TeacherRepository extends Repository<Teacher , Integer> {
  19. //===============使用springdata默认方式=============================
  20. /**
  21. * 根据名字查询老师
  22. * @param name
  23. * @return
  24. */
  25. Teacher findByName(String name);
  26. /**
  27. * 根据班级名称进行查询老师(这里用到模糊匹配like)
  28. * @param classNumber
  29. * @return
  30. */
  31. List<Teacher> findByclassNumberLike(String classNumber);
  32. }

重点分析一波:

(1)首先,我们这个接口是需要继承Repository这个接口

(2)泛型参数:第一个是我们制定这个接口所需要进行操作的实体JavaBean

                         第二个是我们实体JavaBean中主键的类型。(因为我这主键是id,用的Integer类型)

(3)继承的Repository这个接口有什么用?让我们看看源码分析一下

springdata基础

什么?????这个接口啥都没有呀。。。对的,这个接口是什么都没有,就类似Serializable接口一样,就是一个空接口,专业点说就是标记接口。。那么,这个到底有什么用呢?

大家,,认真看认真看!!!!!!!!!()

     第一点Repository是一个空接口,即是一个标记接口。
     第二点若我们定义的接口继承了Repository,则该接口会被IOC容器识别为一个Repository Bean,纳入到IOC容器中,进而可以在该接口中定义满足一定规范的方法。IOC容器中实际存放了继承了Repository的接口的实现类,而这个实现类由spring帮助完成 。在applicationContext.xml中我们配置了springdata:这里的base-package指定了Repository Bean所在的位置,在这个包下的所有的继承了Repository的接口都会被IOC容器识别并纳入到容器中,如果没有继承Repository则IOC容器无法识别。
     第三点:我们也可以通过注解的方式替代继承Repository接口@RepositoryDefinition(domainClass=需要处理的实体类的类型,IdClass=主键的类型)。
     第四点看看它有哪些子类:

springdata基础

那这些子类都有什么用呢?别急,这在我后面都会提到哦!!!!

5:好了,我们来进行单元测试吧!

注意:阿,为什么不需要写接口的实现类吗?是不是博文你忘记说了呀。。。。。不不不不,咱们就是不写,你先按照我上面的接口定义两个方法就可以了。(不过,你要保证你的实体和我的是一样的teacher哦!要不然肯定不行的

  1. package com.hnu.scw;
  2. import com.hnu.scw.model.Teacher;
  3. import com.hnu.scw.repository.TeacherRepository;
  4. import org.junit.Before;
  5. import org.junit.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.context.support.ClassPathXmlApplicationContext;
  9. import java.util.List;
  10. /**
  11. * @ Author :scw
  12. * @ Date :Created in 下午 8:41 2018/6/22 0022
  13. * @ Description:${description}
  14. * @ Modified By:
  15. * @Version: $version$
  16. */
  17. public class SpringDataTest {
  18. //用于加载spring配置文件
  19. private ApplicationContext context = null;
  20. //用于操作老师实体的接口
  21. @Autowired
  22. private TeacherRepository teacherRepository = null;
  23. @Before
  24. public void getContext(){
  25. context = new ClassPathXmlApplicationContext("springdatacontext.xml");
  26. //通过类名进行注入
  27. teacherRepository = context.getBean(TeacherRepository.class);
  28. }
  29. /**
  30. * 直接执行这个测试方法,然后就再去看一下数据库就会发生对应实体中的内容到数据库中了
  31. */
  32. @Test
  33. public void testCreateTableAuto(){
  34. }
  35. /**
  36. * 测试springdata中的findByName方法(没有任何的实现,这就是springdata的强大)
  37. */
  38. @Test
  39. public void testSpringDataFindName(){
  40. Teacher teacher = teacherRepository.findByName("哈哈");
  41. System.out.println(teacher);
  42. }
  43. /**
  44. * 测试使用springdata进行模糊匹配
  45. */
  46. @Test
  47. public void testSpringDataLike(){
  48. List<Teacher> teachers = teacherRepository.findByclassNumberLike("%班班%");
  49. for (Teacher teacher:teachers) {
  50. System.out.println(teacher);
  51. }
  52. }
  53. }

温馨提示:当我们直接上面的代码后,就会发现,竟然竟然能够进行数据操作耶,但是我并没有写实现类,这是为什么为什么为什么呢?

好的,咱们的重点来了,好好看看~~~~

知识点1:为什么只需要在接口中写方法名称,而不需要写实现类就可以进行数据库的操作?

解析:是否还记得我们的接口是继承的Respository这个接口呢?是的,这个就是它的强大的地方。一切的一切都是归根于它。这个原因我在上面已经说过了哦。

知识点2:在接口中方法名称是随便写的吗?有没有什么规范呢?

解析:这个当然不能随便写了,而且我们要实现我们想要的操作,我们必须满足Spring Data定义的规范。

我来分析一下我写的示例的方法,为什么这样命名就可以实现我们想要的操作了。

第一:

springdata基础

首先:findBy就表示我们要进行查询操作,所以,如果你需要进行查询操作,那你就就需要前缀是findBy

其次:Name :这个也不是随便的哦。如果我们想根据实体类中的名字属性进行查询,那么就是Name,如果是想根据班级,那么我们就要写classNumber。当然,里面的参数的命名就是随便的啦,参数名字就没什么影响了

最后:Teacher返回类型:这个没什么特别,我们查询的就是这个实体的数据,当然就是返回这个类型的对象啦。

第二:

springdata基础

首先:findBy这个和上面解释一样,我就不多说。

其次:classNumber这个也不多说,因为,我是要进行这个属性的模糊查询呀!

最后:Like:这个可是很重要的哦。这后缀就代表是进行模糊匹配啦。所以,如果你要进行模糊匹配就要Like结束方法名

OK,如果这样,那我数据库操作麻烦起来的话,那么方法名不是特别长,特别难记了,而且好多规范都不知道,怎么办呢?别着急呀,下面我就来给你介绍一下,有哪些命令的规范。。(其实嘛,后面当然有解决办法啦~哈哈)

关键字 方法命名 sql where字句
And findByNameAndPwd where name= ? and pwd =?
Or findByNameOrSex where name= ? or sex=?
Is,Equals findById,findByIdEquals where id= ?
Between findByIdBetween where id between ? and ?
LessThan findByIdLessThan where id < ?
LessThanEquals findByIdLessThanEquals where id <= ?
GreaterThan findByIdGreaterThan where id > ?
GreaterThanEquals findByIdGreaterThanEquals where id > = ?
After findByIdAfter where id > ?
Before findByIdBefore where id < ?
IsNull findByNameIsNull where name is null
isNotNull,NotNull findByNameNotNull where name is not null
Like findByNameLike where name like ?
NotLike findByNameNotLike where name not like ?

StartingWith

findByNameStartingWith where name like '?%'
EndingWith findByNameEndingWith where name like '%?'
Containing findByNameContaining where name like '%?%'
OrderBy findByIdOrderByXDesc where id=? order by x desc
Not findByNameNot where name <> ?
In findByIdIn(Collection<?> c) where id in (?)
NotIn findByIdNotIn(Collection<?> c) where id not  in (?)
True

findByAaaTue

where aaa = true
False findByAaaFalse where aaa = false
IgnoreCase findByNameIgnoreCase where UPPER(name)=UPPER(?)

咳咳咳咳,这么多,记不住,怎么办?那么,我就教你进一步的优化~毕竟先苦后甜嘛~~~~

(二)通过@Query注解来优化Spring Data接口中的方法

我们在上面已经看到了,一般接口定义方法的名字是比较麻烦的,当然,如果Spring Data只能做到这样的程度,那就也太low了,所以如果解决上面的方法呢?很简单,通过注解就可以解决了。

1:示例代码:(这个还是写在上面接口中即可,请注意我代码里面的注释)

  1. //==============使用query注解开发==============================================
  2. /**
  3. * 通过query注解进行开发模糊匹配(利用索引参数的方法)
  4. * @param classNumber
  5. * @return
  6. */
  7. @Query("select t from Teacher t where t.classNumber like %?1%")
  8. List<Teacher> queryTeacher(String classNumber);
  9. /**
  10. * 通过老师的名字来进行查询数据
  11. * @param name
  12. * @return
  13. */
  14. @Query("select t from Teacher t where t.name = ?1")
  15. Teacher queryTeacherByName(String name );
  16. /**
  17. * 通过老师的名字来进行查询数据(利用命名参数的方法,注意query注解的写法不一样的)
  18. * @param name
  19. * @return
  20. */
  21. @Query("select t from Teacher t where t.name = :name")
  22. Teacher queryTeacherByName2(@Param("name") String name );
  23. /**
  24. * 使用原生的SQL语句进行操作(注意from这时候用的就是数据库的表名,而不是实体类名)
  25. * 必须添加nativeQuery = true,因为默认是false的
  26. * @return
  27. */
  28. @Query(nativeQuery = true , value = "select count(1) from teacher")
  29. long countTeacherNumber();

2:编写单元测试;

  1. /**
  2. * 测试使用springdata中的query注解进行开发模糊查询
  3. */
  4. @Test
  5. public void testQueryTeacher(){
  6. List<Teacher> teachers = teacherRepository.queryTeacher("班班");
  7. for (Teacher teacher:teachers) {
  8. System.out.println(teacher);
  9. }
  10. }
  11. /**
  12. * 测试通过占位符进行操作查询
  13. */
  14. @Test
  15. public void testQueryTeacherByName(){
  16. Teacher teacher = teacherRepository.queryTeacherByName("哈哈");
  17. System.out.println(teacher);
  18. }
  19. /**
  20. * 测试通过别名进行操作查询
  21. */
  22. @Test
  23. public void testQueryTeacherByName2(){
  24. Teacher teacher = teacherRepository.queryTeacherByName2("哈哈");
  25. System.out.println(teacher);
  26. }
  27. /**
  28. * 测试使用原生的SQL语句进行开发
  29. */
  30. @Test
  31. public void testCountTeacherNumber(){
  32. long number = teacherRepository.countTeacherNumber();
  33. System.out.println("数据总条数为:" + number);
  34. }

(三)如何使用Spring Data进行删除更新的数据库操作

我们之前都是写的查询操作,那么如果进行更新和删除操作,是不是也是一样的?

然而,请注意,并不是的,而且特别要注意下面两点:

(1)对于更新和删除操作,必须在接口的方法上面添加@Modifying注解,这样就用于标识这是一个修改的操作

(2)必须在调用这个接口方法的地方(一般就是service层)使用事务,即用@Transactional注解进行标识。

示例代码:

1:编写接口方法:

  1. //================进行springdata的更新删除的处理======================
  2. /**
  3. * 根据老师表的id进行修改对应数据的老师名字
  4. * 必须要添加@Modifying注解,并且要在调用的方法上添加事务注解@Transactional
  5. * @param name
  6. * @param id
  7. */
  8. @Modifying
  9. @Query("update Teacher t set t.name = ?1 where t.id = ?2")
  10. void updateTeacherById(String name , Integer id);:

2:编写service层代码

  1. package com.hnu.scw.service;
  2. import com.hnu.scw.model.Teacher;
  3. import com.hnu.scw.repository.TeacherCrudRespository;
  4. import com.hnu.scw.repository.TeacherRepository;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import javax.transaction.Transactional;
  8. import java.util.List;
  9. /**
  10. * @ Author :scw
  11. * @ Date :Created in 下午 5:29 2018/6/23 0023
  12. * @ Description:编写springdata相关的service层代码
  13. * @ Modified By:
  14. * @Version: $version$
  15. */
  16. @Service
  17. public class SpringDataService {
  18. @Autowired
  19. private TeacherRepository teacherRepository;
  20. @Autowired
  21. private TeacherCrudRespository teacherCrudRespository;
  22. /**
  23. * 根据id进行修改老师的名字
  24. * @param name
  25. * @param id
  26. */
  27. @Transactional
  28. public void updateTeacher(String name , Integer id){
  29. teacherRepository.updateTeacherById(name , id);
  30. }
  31. }

3:单元测试代码:

  1. package com.hnu.scw.service;
  2. import com.hnu.scw.model.Teacher;
  3. import com.hnu.scw.repository.TeacherRepository;
  4. import org.junit.Before;
  5. import org.junit.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.context.support.ClassPathXmlApplicationContext;
  9. import java.util.ArrayList;
  10. /**
  11. * @ Author :scw
  12. * @ Date :Created in 下午 5:27 2018/6/23 0023
  13. * @ Description:测试service层的方法
  14. * @ Modified By:
  15. * @Version: $version$
  16. */
  17. public class SpringDataServiceTest {
  18. //用于加载spring配置文件
  19. private ApplicationContext context = null;
  20. @Autowired
  21. private SpringDataService springDataService = null ;
  22. @Before
  23. public void getContext(){
  24. context = new ClassPathXmlApplicationContext("springdatacontext.xml");
  25. //通过类名进行注入
  26. springDataService = context.getBean(SpringDataService.class);
  27. }
  28. /**
  29. * 测试springdata的更新操作的方法
  30. * 注意点:接口必须添加@Modifying注解
  31. * 调用层service必须有事务注解@Transactional
  32. */
  33. @Test
  34. public void testUpdateTeacher(){
  35. springDataService.updateTeacher("呵呵" , 1);
  36. }
  37. }:

Spring Data的进阶

    根据我们上面的内容,已经学会了基本的Spring Data的操作。那么,它就这么点技能么?当然不是,请看下面的内容。

(一)接口继承CrudRespository接口

说明: CrudRepository 接口继承于 Repository 接口,并新增了简单的增、删、查等方法。

主要的方法如下:

springdata基础

示例代码:

  1. package com.hnu.scw.repository;
  2. import com.hnu.scw.model.Teacher;
  3. import org.springframework.data.repository.CrudRepository;
  4. /**
  5. * @ Author :scw
  6. * @ Date :Created in 下午 5:38 2018/6/23 0023
  7. * @ Description:通过继承CrudRespository接口(因为可以快速进行crud相关的方法开发)
  8. * @ Modified By:
  9. * @Version: $version$
  10. */
  11. public interface TeacherCrudRespository extends CrudRepository<Teacher , Integer>{
  12. }

示例单元测试类:大家就可以根据我上面贴的方法进行随便编写就好了啦。就不多写测试方法了~~~~~~

(二)接口继承JpaRespository接口

说明:JpaRepository支持接口规范方法名查询。意思是如果在接口中定义的查询方法符合它的命名规则,就可以不用写实现了。这个我在前面就说了有哪些命名规则的哦~

主要的接口如下:

springdata基础

示例代码:

  1. package com.hnu.scw.repository;
  2. import com.hnu.scw.model.Teacher;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. /**
  5. * @ Author :scw
  6. * @ Date :Created in 下午 5:59 2018/6/23 0023
  7. * @ Description:测试继承JpaRepository接口的方法
  8. * @ Modified By:
  9. * @Version: $version$
  10. */
  11. public interface TeacherJpaRepository extends JpaRepository<Teacher ,Integer>{
  12. }

单元测试代码:

  1. package com.hnu.scw;
  2. import com.hnu.scw.model.Teacher;
  3. import com.hnu.scw.repository.TeacherJpaRepository;
  4. import com.hnu.scw.repository.TeacherPagingAndSortRespository;
  5. import org.junit.Before;
  6. import org.junit.Test;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;
  10. /**
  11. * @ Author :scw
  12. * @ Date :Created in 下午 6:00 2018/6/23 0023
  13. * @ Description:测试继承Respositoty接口的相关的操作
  14. * @ Modified By:
  15. * @Version: $version$
  16. */
  17. public class JpaRespositotyTest {
  18. //用于加载spring配置文件
  19. private ApplicationContext context = null;
  20. //用于操作老师实体的接口
  21. @Autowired
  22. private TeacherJpaRepository teacherJpaRepository = null;
  23. @Before
  24. public void getContext(){
  25. context = new ClassPathXmlApplicationContext("springdatacontext.xml");
  26. //通过类名进行注入
  27. teacherJpaRepository = context.getBean(TeacherJpaRepository.class);
  28. }
  29. /**
  30. * 测试JpaRepository接口中相关的查找数据的方法
  31. */
  32. @Test
  33. public void testJpaFind(){
  34. //查询id=20的数据
  35. Teacher oneTeacher = teacherJpaRepository.findOne(20);
  36. System.out.println(oneTeacher);
  37. //判断id=100的数据是否存在于数据库中
  38. boolean exists = teacherJpaRepository.exists(100);
  39. System.out.println("数据存在吗?" + exists);
  40. }
  41. }

(三)接口继承PagingAndSortRespository接口

说明:这个接口主要就是实现了分页和排序的方法。。。所以,分页很重要哦~

方法接口如下:

springdata基础

接口示例代码:

  1. package com.hnu.scw.repository;
  2. import com.hnu.scw.model.Teacher;
  3. import org.springframework.data.repository.PagingAndSortingRepository;
  4. /**
  5. * @ Author :scw
  6. * @ Date :Created in 下午 5:48 2018/6/23 0023
  7. * @ Description:通过继承PagingAndSortRespository接口来快速进行分页开发
  8. * @ Modified By:
  9. * @Version: $version$
  10. */
  11. public interface TeacherPagingAndSortRespository extends PagingAndSortingRepository<Teacher ,Integer>{
  12. }
单元测试代码:
  1. package com.hnu.scw;
  2. import com.hnu.scw.model.Teacher;
  3. import com.hnu.scw.repository.TeacherPagingAndSortRespository;
  4. import com.hnu.scw.repository.TeacherRepository;
  5. import org.junit.Before;
  6. import org.junit.Test;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;
  10. import org.springframework.data.domain.Page;
  11. import org.springframework.data.domain.PageRequest;
  12. import org.springframework.data.domain.Sort;
  13. /**
  14. * @ Author :scw
  15. * @ Date :Created in 下午 5:49 2018/6/23 0023
  16. * @ Description:测试PagingAndSortRespository接口的分页方法
  17. * @ Modified By:
  18. * @Version: $version$
  19. */
  20. public class PagingAndSortRespositoryTest {
  21. //用于加载spring配置文件
  22. private ApplicationContext context = null;
  23. //用于操作老师实体的接口
  24. @Autowired
  25. private TeacherPagingAndSortRespository teacherPagingAndSortRespository = null;
  26. @Before
  27. public void getContext(){
  28. context = new ClassPathXmlApplicationContext("springdatacontext.xml");
  29. //通过类名进行注入
  30. teacherPagingAndSortRespository = context.getBean(TeacherPagingAndSortRespository.class);
  31. }
  32. /**
  33. * 测试通过继承PagingAndSortRespository进行分页的相关开发
  34. * 相当的方便
  35. */
  36. @Test
  37. public void testPagingTeacher(){
  38. PageRequest pageRequest = new PageRequest(0, 5);
  39. Page<Teacher> page = teacherPagingAndSortRespository.findAll(pageRequest);
  40. System.out.println("查询的总页数:" + page.getTotalPages());
  41. System.out.println("查询的总数据条数:" + page.getTotalElements());
  42. System.out.println("查询的当前页数:" + (page.getNumber() + 1));
  43. System.out.println("查询的数据的内容:" + page.getContent());
  44. System.out.println("查询的当前页的数据条数:" + page.getNumberOfElements());
  45. }
  46. /**
  47. * 测试分页和排序的方法
  48. */
  49. @Test
  50. public void testPagingAndSortTeacher(){
  51. //按照id的降序进行排序
  52. Sort.Order sortOrder = new Sort.Order(Sort.Direction.DESC, "id");
  53. //构建排序对象
  54. Sort sort = new Sort(sortOrder);
  55. //把分页和排序对象放入参数
  56. PageRequest pageRequest = new PageRequest(0, 5 , sort);
  57. Page<Teacher> page = teacherPagingAndSortRespository.findAll(pageRequest);
  58. System.out.println("查询的总页数:" + page.getTotalPages());
  59. System.out.println("查询的总数据条数:" + page.getTotalElements());
  60. System.out.println("查询的当前页数:" + (page.getNumber() + 1));
  61. System.out.println("查询的数据的内容:" + page.getContent());
  62. System.out.println("查询的当前页的数据条数:" + page.getNumberOfElements());
  63. }
  64. }

(四)接口继承JpaSpecificationExcutor接口

说明:不属于Repository体系,实现一组 JPA Criteria 查询相关的方法。Specification:封装 JPA Criteria 查询条件。通常使用匿名内部类的方式来创建该接口的对象。

主要接口方法如下:主要就是条件过滤,比如我们在分页的时候需要一些条件,这样就可以更好的进行分页处理。

springdata基础

示例代码如下:(用于实现分页和过滤的作用)

  1. package com.hnu.scw.repository;
  2. import com.hnu.scw.model.Teacher;
  3. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  4. import org.springframework.data.repository.PagingAndSortingRepository;
  5. /**
  6. * @ Author :scw
  7. * @ Date :Created in 下午 6:04 2018/6/23 0023
  8. * @ Description:继承JpaSpecificationExecutorRepository接口
  9. * @ Modified By:
  10. * @Version: $version$
  11. */
  12. public interface TeacherJpaSpecificationExecutorRepository extends PagingAndSortingRepository<Teacher , Integer> ,JpaSpecificationExecutor<Teacher >{
  13. }

单元测试如下:

  1. package com.hnu.scw;
  2. import com.hnu.scw.model.Teacher;
  3. import com.hnu.scw.repository.TeacherJpaSpecificationExecutorRepository;
  4. import com.hnu.scw.repository.TeacherRepository;
  5. import jdk.nashorn.interna