1 简介

  • 对于数据访问层,无论是SQL还是NoSQL,SpringBoot默认采用整合SpringData的方式进行统一处理,添加大量自动配置,屏蔽了很多设置 。引入各种xxxTemplate、xxxRepository来简化我们对数据访问层的操作。
  • 对于我们来说只需要进行简单的设置即可。

2 整合基本JDBC和数据源

2.1 导入相关jar包的maven坐标

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-jdbc</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>mysql</groupId>
  11. <artifactId>mysql-connector-java</artifactId>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-test</artifactId>
  20. <scope>test</scope>
  21. </dependency>

2.2 配置application.yml

  1. spring:
  2. datasource:
  3. username: root
  4. password: 123456
  5. url: jdbc:mysql://192.168.179.100:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
  6. driver-class-name: com.mysql.jdbc.Driver
  • 默认使用的数据源是org.apache.tomcat.jdbc.pool.DataSource。
  • 数据源的相关配置都在DataSourceProperties里面。
  • 自动配置原理。
  • SpringBoot和数据访问 - 图1参考org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration,根据配置创建数据源,默认使用Tomcat连接池,可以使用spring.datasource.type指定自定义的数据源类型。
  1. abstract class DataSourceConfiguration {
  2. /**
  3. * Tomcat Pool DataSource configuration.
  4. */
  5. @ConditionalOnClass(org.apache.tomcat.jdbc.pool.DataSource.class)
  6. @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.tomcat.jdbc.pool.DataSource", matchIfMissing = true)
  7. static class Tomcat extends DataSourceConfiguration {
  8. @Bean
  9. @ConfigurationProperties(prefix = "spring.datasource.tomcat")
  10. public org.apache.tomcat.jdbc.pool.DataSource dataSource(
  11. DataSourceProperties properties) {
  12. org.apache.tomcat.jdbc.pool.DataSource dataSource = createDataSource(
  13. properties, org.apache.tomcat.jdbc.pool.DataSource.class);
  14. DatabaseDriver databaseDriver = DatabaseDriver
  15. .fromJdbcUrl(properties.determineUrl());
  16. String validationQuery = databaseDriver.getValidationQuery();
  17. if (validationQuery != null) {
  18. dataSource.setTestOnBorrow(true);
  19. dataSource.setValidationQuery(validationQuery);
  20. }
  21. return dataSource;
  22. }
  23. }
  24. /**
  25. * Hikari DataSource configuration.
  26. */
  27. @ConditionalOnClass(HikariDataSource.class)
  28. @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.zaxxer.hikari.HikariDataSource", matchIfMissing = true)
  29. static class Hikari extends DataSourceConfiguration {
  30. @Bean
  31. @ConfigurationProperties(prefix = "spring.datasource.hikari")
  32. public HikariDataSource dataSource(DataSourceProperties properties) {
  33. return createDataSource(properties, HikariDataSource.class);
  34. }
  35. }
  36. /**
  37. * DBCP DataSource configuration.
  38. *
  39. * @deprecated as of 1.5 in favor of DBCP2
  40. */
  41. @ConditionalOnClass(org.apache.commons.dbcp.BasicDataSource.class)
  42. @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.commons.dbcp.BasicDataSource", matchIfMissing = true)
  43. @Deprecated
  44. static class Dbcp extends DataSourceConfiguration {
  45. @Bean
  46. @ConfigurationProperties(prefix = "spring.datasource.dbcp")
  47. public org.apache.commons.dbcp.BasicDataSource dataSource(
  48. DataSourceProperties properties) {
  49. org.apache.commons.dbcp.BasicDataSource dataSource = createDataSource(
  50. properties, org.apache.commons.dbcp.BasicDataSource.class);
  51. DatabaseDriver databaseDriver = DatabaseDriver
  52. .fromJdbcUrl(properties.determineUrl());
  53. String validationQuery = databaseDriver.getValidationQuery();
  54. if (validationQuery != null) {
  55. dataSource.setTestOnBorrow(true);
  56. dataSource.setValidationQuery(validationQuery);
  57. }
  58. return dataSource;
  59. }
  60. }
  61. /**
  62. * DBCP DataSource configuration.
  63. */
  64. @ConditionalOnClass(org.apache.commons.dbcp2.BasicDataSource.class)
  65. @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.commons.dbcp2.BasicDataSource", matchIfMissing = true)
  66. static class Dbcp2 extends DataSourceConfiguration {
  67. @Bean
  68. @ConfigurationProperties(prefix = "spring.datasource.dbcp2")
  69. public org.apache.commons.dbcp2.BasicDataSource dataSource(
  70. DataSourceProperties properties) {
  71. return createDataSource(properties,
  72. org.apache.commons.dbcp2.BasicDataSource.class);
  73. }
  74. }
  75. //其他略
  76. }
  • SpringBoot和数据访问 - 图2SpringBoot默认支持org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、org.apache.commons.dbcp.BasicDataSource和org.apache.commons.dbcp2.BasicDataSource数据源。
  • SpringBoot和数据访问 - 图3自定义数据源类型:
  1. abstract class DataSourceConfiguration {
  2. /**
  3. * Generic DataSource configuration.
  4. */
  5. @ConditionalOnMissingBean(DataSource.class)
  6. @ConditionalOnProperty(name = "spring.datasource.type")
  7. static class Generic {
  8. @Bean
  9. public DataSource dataSource(DataSourceProperties properties) {
  10. return properties.initializeDataSourceBuilder().build();
  11. }
  12. }
  13. //其他略
  14. }
  • SpringBoot和数据访问 - 图4DataSourceInitializer是ApplicationListener,其作用是:
    • ①运行建表语句,sql脚本的规则是schema-*.sql。
    • ②运行插入数据的语句,sql脚本的规则是data-*.sql。
  1. @Configuration
  2. @ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })
  3. @EnableConfigurationProperties(DataSourceProperties.class)
  4. @Import({ Registrar.class, DataSourcePoolMetadataProvidersConfiguration.class })
  5. public class DataSourceAutoConfiguration {
  6. @Bean
  7. @ConditionalOnMissingBean
  8. public DataSourceInitializer dataSourceInitializer(DataSourceProperties properties,
  9. ApplicationContext applicationContext) {
  10. return new DataSourceInitializer(properties, applicationContext);
  11. }
  12. //其他略
  13. }
  • SpringBoot和数据访问 - 图5自动配置了JdbcTemplate和NamedParameterJdbcTemplate,用来操作数据库。
  1. package org.springframework.boot.autoconfigure.jdbc;
  2. import javax.sql.DataSource;
  3. import org.springframework.boot.autoconfigure.AutoConfigureAfter;
  4. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  5. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  6. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  7. import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.context.annotation.Primary;
  11. import org.springframework.jdbc.core.JdbcOperations;
  12. import org.springframework.jdbc.core.JdbcTemplate;
  13. import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
  14. import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
  15. @Configuration
  16. @ConditionalOnClass({ DataSource.class, JdbcTemplate.class })
  17. @ConditionalOnSingleCandidate(DataSource.class)
  18. @AutoConfigureAfter(DataSourceAutoConfiguration.class)
  19. public class JdbcTemplateAutoConfiguration {
  20. private final DataSource dataSource;
  21. public JdbcTemplateAutoConfiguration(DataSource dataSource) {
  22. this.dataSource = dataSource;
  23. }
  24. @Bean
  25. @Primary
  26. @ConditionalOnMissingBean(JdbcOperations.class)
  27. public JdbcTemplate jdbcTemplate() {
  28. return new JdbcTemplate(this.dataSource);
  29. }
  30. @Bean
  31. @Primary
  32. @ConditionalOnMissingBean(NamedParameterJdbcOperations.class)
  33. public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
  34. return new NamedParameterJdbcTemplate(this.dataSource);
  35. }
  36. }

2.3 整合数据源Druid

2.3.1 引入druid

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>druid-spring-boot-starter</artifactId>
  4. <version>1.1.23</version>
  5. </dependency>
  1. spring:
  2. datasource:
  3. username: root
  4. password: 123456
  5. url: jdbc:mysql://192.168.64.101:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
  6. driver-class-name: com.mysql.jdbc.Driver
  7. type: com.alibaba.druid.pool.DruidDataSource
  8. # 数据源的其他配置
  9. druid:
  10. # 初始化
  11. initial-size: 5
  12. # 最小
  13. min-idle: 5
  14. # 最大
  15. max-active: 20
  16. # 连接等待超时时间
  17. max-wait: 60000
  18. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  19. time-between-eviction-runs-millis: 60000
  20. # 配置一个连接在池中最小生存的时间,单位是毫秒
  21. min-evictable-idle-time-millis: 300000
  22. validation-query: SELECT 1 FROM DUAL
  23. test-on-borrow: false
  24. test-while-idle: true
  25. test-on-return: false
  26. # 打开PSCache,并且指定每个连接上PSCache的大小
  27. pool-prepared-statements: true
  28. max-pool-prepared-statement-per-connection-size: 20
  29. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  30. filters: stat,wall,log4j
  31. #合并多个DruidDataSource的监控数据
  32. use-global-data-source-stat: true
  33. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  34. connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  35. # 配置DruidStatFilter
  36. web-stat-filter:
  37. enabled: true
  38. url-pattern: "/*"
  39. exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
  40. # 配置DruidStatViewServlet
  41. stat-view-servlet:
  42. enabled: true
  43. url-pattern: "/druid/*"
  44. # IP白名单(没有配置或者为空,则允许所有访问)
  45. # allow:
  46. # IP黑名单 (存在共同时,deny优先于allow)
  47. # deny:
  48. # 禁用HTML页面上的“Reset All”功能
  49. reset-enable: false
  50. # 登录名
  51. login-username: admin
  52. # 登录密码
  53. login-password: 123456

3 整合Mybatis

3.1 导入相关jar包的Maven坐标

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-configuration-processor</artifactId>
  4. <optional>true</optional>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-data-jpa</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-jdbc</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-test</artifactId>
  21. <scope>test</scope>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-web</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>com.alibaba</groupId>
  29. <artifactId>druid-spring-boot-starter</artifactId>
  30. <version>1.1.23</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.mybatis.spring.boot</groupId>
  38. <artifactId>mybatis-spring-boot-starter</artifactId>
  39. <version>2.1.3</version>
  40. </dependency>

3.2 sql脚本

  1. DROP TABLE IF EXISTS `employee`;
  2. CREATE TABLE `employee` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT,
  4. `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  5. `gender` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  6. PRIMARY KEY (`id`) USING BTREE
  7. ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

3.3 创建JavaBean

  1. package com.sunxiaping.springboot.domain;
  2. public class Employee {
  3. private Integer id;
  4. private String name;
  5. private String gender;
  6. public Integer getId() {
  7. return id;
  8. }
  9. public void setId(Integer id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public String getGender() {
  19. return gender;
  20. }
  21. public void setGender(String gender) {
  22. this.gender = gender;
  23. }
  24. @Override
  25. public String toString() {
  26. return "Employee{" +
  27. "id=" + id +
  28. ", name='" + name + '\'' +
  29. ", gender='" + gender + '\'' +
  30. '}';
  31. }
  32. }

3.4 注解版

  • 创建Mapper接口:
  1. package com.sunxiaping.springboot.mapper;
  2. import com.sunxiaping.springboot.domain.Employee;
  3. import org.apache.ibatis.annotations.Insert;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.apache.ibatis.annotations.Options;
  6. //指定这是一个操作数据库的Mapper
  7. @Mapper
  8. public interface EmployeeMapper {
  9. @Options(useGeneratedKeys = true,keyProperty = "id")
  10. @Insert("INSERT into `employee` (`name`,`gender`) values (#{name},#{gender})")
  11. void save(Employee employee);
  12. }
  • 在SpringBoot的启动类上加上@MapperScan注解,指定Mapper接口所在的包名
  1. package com.sunxiaping.springboot;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.boot.web.servlet.ServletComponentScan;
  6. /**
  7. * 主程序,用来启动SpringBoot应用
  8. */
  9. @SpringBootApplication
  10. @ServletComponentScan
  11. //指定扫描的Mapper接口的包名
  12. @MapperScan(basePackages = "com.sunxiaping.springboot.mapper")
  13. public class WebApplication {
  14. public static void main(String[] args) {
  15. SpringApplication.run(WebApplication.class, args);
  16. }
  17. }
  • 自定义Mybatis规则:
  1. package com.sunxiaping.springboot.config;
  2. import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. @Configuration
  6. public class MybatisConfig {
  7. @Bean
  8. public ConfigurationCustomizer configurationCustomizer() {
  9. return (configuration)->{
  10. //开启驼峰命名
  11. configuration.setMapUnderscoreToCamelCase(true);
  12. };
  13. }
  14. }
  • 测试:
  1. package com.sunxiaping.springboot;
  2. import com.sunxiaping.springboot.domain.Employee;
  3. import com.sunxiaping.springboot.mapper.EmployeeMapper;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. @RunWith(SpringRunner.class)
  10. @SpringBootTest
  11. public class SpringbootApplicationTests {
  12. @Autowired
  13. private EmployeeMapper employeeMapper;
  14. @Test
  15. public void test() {
  16. Employee employee = new Employee();
  17. employee.setName("张三");
  18. employee.setGender("男");
  19. employeeMapper.save(employee);
  20. System.out.println("employee = " + employee);
  21. }
  22. }

3.5 配置版

  • 编写EmployeeMapper接口:
  1. package com.sunxiaping.springboot.mapper;
  2. import com.sunxiaping.springboot.domain.Employee;
  3. import org.apache.ibatis.annotations.Mapper;
  4. //指定这是一个操作数据库的Mapper
  5. @Mapper
  6. public interface EmployeeMapper {
  7. void save( Employee employee);
  8. }
  • 编写mybatis-config.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <settings>
  7. <setting name="mapUnderscoreToCamelCase" value="true"/>
  8. </settings>
  9. </configuration>
  • 编写EmployeeMapper.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.sunxiaping.springboot.mapper.EmployeeMapper">
  6. <insert id="save" parameterType="com.sunxiaping.springboot.domain.Employee" useGeneratedKeys="true" keyProperty="id">
  7. INSERT INTO `employee`(`name`,`gender`)
  8. VALUES (#{name},#{gender})
  9. </insert>
  10. </mapper>
  • application.yml
  1. spring:
  2. # 数据源
  3. datasource:
  4. username: root
  5. password: 123456
  6. url: jdbc:mysql://192.168.64.101:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
  7. driver-class-name: com.mysql.jdbc.Driver
  8. type: com.alibaba.druid.pool.DruidDataSource
  9. # 数据源的其他配置
  10. druid:
  11. # 初始化
  12. initial-size: 5
  13. # 最小
  14. min-idle: 5
  15. # 最大
  16. max-active: 20
  17. # 连接等待超时时间
  18. max-wait: 60000
  19. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  20. time-between-eviction-runs-millis: 60000
  21. # 配置一个连接在池中最小生存的时间,单位是毫秒
  22. min-evictable-idle-time-millis: 300000
  23. validation-query: SELECT 1 FROM DUAL
  24. test-on-borrow: false
  25. test-while-idle: true
  26. test-on-return: false
  27. # 打开PSCache,并且指定每个连接上PSCache的大小
  28. pool-prepared-statements: true
  29. max-pool-prepared-statement-per-connection-size: 20
  30. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  31. filters: stat,wall,log4j
  32. #合并多个DruidDataSource的监控数据
  33. use-global-data-source-stat: true
  34. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  35. connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  36. # 配置DruidStatFilter
  37. web-stat-filter:
  38. enabled: true
  39. url-pattern: "/*"
  40. exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
  41. # 配置DruidStatViewServlet
  42. stat-view-servlet:
  43. enabled: true
  44. url-pattern: "/druid/*"
  45. # IP白名单(没有配置或者为空,则允许所有访问)
  46. # allow:
  47. # IP黑名单 (存在共同时,deny优先于allow)
  48. # deny:
  49. # 禁用HTML页面上的“Reset All”功能
  50. reset-enable: false
  51. # 登录名
  52. login-username: admin
  53. # 登录密码
  54. login-password: 123456
  55. mybatis:
  56. mapper-locations: classpath:com/sunxiaping/springboot/mapper/*.xml
  57. config-location: classpath:mybatis-config.xml
  • 测试:
  1. package com.sunxiaping.springboot;
  2. import com.sunxiaping.springboot.domain.Employee;
  3. import com.sunxiaping.springboot.mapper.EmployeeMapper;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. @RunWith(SpringRunner.class)
  10. @SpringBootTest
  11. public class SpringbootApplicationTests {
  12. @Autowired
  13. private EmployeeMapper employeeMapper;
  14. @Test
  15. public void test() {
  16. Employee employee = new Employee();
  17. employee.setName("张三");
  18. employee.setGender("男");
  19. employeeMapper.save(employee);
  20. System.out.println("employee = " + employee);
  21. }
  22. }

4 整合JPA

4.1 导入相关jar包的Maven坐标

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-configuration-processor</artifactId>
  4. <optional>true</optional>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-data-jpa</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-jdbc</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-test</artifactId>
  21. <scope>test</scope>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-web</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>com.alibaba</groupId>
  29. <artifactId>druid-spring-boot-starter</artifactId>
  30. <version>1.1.23</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-data-jpa</artifactId>
  35. </dependency>

4.2 编写实体类

  1. package com.sunxiaping.springboot.domain;
  2. import javax.persistence.*;
  3. @Entity
  4. @Table(name = "`employee`")
  5. public class Employee {
  6. @Id
  7. @GeneratedValue(strategy = GenerationType.IDENTITY)
  8. private Integer id;
  9. @Column(name = "`name`")
  10. private String name;
  11. @Column(name = "`gender`")
  12. private String gender;
  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 String getGender() {
  26. return gender;
  27. }
  28. public void setGender(String gender) {
  29. this.gender = gender;
  30. }
  31. @Override
  32. public String toString() {
  33. return "Employee{" +
  34. "id=" + id +
  35. ", name='" + name + '\'' +
  36. ", gender='" + gender + '\'' +
  37. '}';
  38. }
  39. }

4.3 编写application.yml

  1. spring:
  2. # 数据源
  3. datasource:
  4. username: root
  5. password: 123456
  6. url: jdbc:mysql://192.168.64.101:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
  7. driver-class-name: com.mysql.jdbc.Driver
  8. type: com.alibaba.druid.pool.DruidDataSource
  9. # 数据源的其他配置
  10. druid:
  11. # 初始化
  12. initial-size: 5
  13. # 最小
  14. min-idle: 5
  15. # 最大
  16. max-active: 20
  17. # 连接等待超时时间
  18. max-wait: 60000
  19. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  20. time-between-eviction-runs-millis: 60000
  21. # 配置一个连接在池中最小生存的时间,单位是毫秒
  22. min-evictable-idle-time-millis: 300000
  23. validation-query: SELECT 1 FROM DUAL
  24. test-on-borrow: false
  25. test-while-idle: true
  26. test-on-return: false
  27. # 打开PSCache,并且指定每个连接上PSCache的大小
  28. pool-prepared-statements: true
  29. max-pool-prepared-statement-per-connection-size: 20
  30. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  31. filters: stat,wall,log4j
  32. #合并多个DruidDataSource的监控数据
  33. use-global-data-source-stat: true
  34. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  35. connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  36. # 配置DruidStatFilter
  37. web-stat-filter:
  38. enabled: true
  39. url-pattern: "/*"
  40. exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
  41. # 配置DruidStatViewServlet
  42. stat-view-servlet:
  43. enabled: true
  44. url-pattern: "/druid/*"
  45. # IP白名单(没有配置或者为空,则允许所有访问)
  46. # allow:
  47. # IP黑名单 (存在共同时,deny优先于allow)
  48. # deny:
  49. # 禁用HTML页面上的“Reset All”功能
  50. reset-enable: false
  51. # 登录名
  52. login-username: admin
  53. # 登录密码
  54. login-password: 123456
  55. jpa:
  56. show-sql: true
  57. open-in-view: true
  58. hibernate:
  59. ddl-auto: update

4.3 编写Repository

package com.sunxiaping.springboot.repository;

import com.sunxiaping.springboot.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface EmployeeRepository extends JpaRepository<Employee,Integer>, JpaSpecificationExecutor<Employee> {

}

4.4 测试

package com.sunxiaping.springboot;

import com.sunxiaping.springboot.domain.Employee;
import com.sunxiaping.springboot.repository.EmployeeRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {

    @Autowired
    private EmployeeRepository employeeRepository;


    @Test
    public void test() {
        System.out.println("employeeRepository = " + employeeRepository);

        List<Employee> employeeList = employeeRepository.findAll();

        System.out.println("employeeList = " + employeeList);

    }
}