SpringBoot与数据访问

1、整合基本JDBC与数据源

1.1 查看各种场景JDBC有关的场景启动器。

Spring官网

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>

配置文件:

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.15.22:3306/jdbc
    driver-class-name: com.mysql.jdbc.Driver

效果:

  • 默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源
  • 数据源的相关配置都在DataSourceProperties里面

1.2 自动配置原理

org.springframework.boot.autoconfigure.jdbc

  • 参考DataSourceConfiguration,根据配置创建数据源,默认使用Tomcat连接池;可以使用spring.datasource.type指定自定义的数据源类型;
  • SpringBoot默认可以支持以下数据源:
org.apache.tomcat.jdbc.pool.DataSource
HikariDataSource
BasicDataSource
  • 自定义数据源类型
@ConditionalOnMissingBean({DataSource.class})
@ConditionalOnProperty(
  name = {"spring.datasource.type"}
)
static class Generic {
  Generic() {
  }

  @Bean
  public DataSource dataSource(DataSourceProperties properties) {
    // 使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
    return properties.initializeDataSourceBuilder().build();
  }
}
  • DataSourceAutoConfiguration.class中,有DataSourceInitializer继承自ApplicationListener

    作用:

    • runSchemaScripts();运行建表语句

    • runDataScripts();运行插入数据的sql语句

    • 默认只需要将文件命名为:

      schema-*.sql、data-*.sql
      默认规则:必须命名schema.sql,schema-all.sql;
      
    • 可以使用配置文件指定位置

      spring:
        datasource:
          username: root
          password: 123456
          url: jdbc:mysql://192.168.15.22:3306/jdbc
          driver-class-name: com.mysql.jdbc.Driver
          schema:
            - classpath:department.sql
      
  • 操作数据库:自动配置了JdbcTemplate操作数据库

2、整合Druid数据源

在Maven公共库中搜索Druid,找到其Maven依赖:

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>

在配置文件中加入配置:

spring:
  # 数据源基本配置
  datasource:
    # 与DataSourceProperties.class下的属性一一对应
    username: root
    password: 123456
    url: jdbc:mysql://192.168.8.156:3306/jdbc
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
#    schema:
#      - classpath:department.sql
    # 数据源其他配置, 底部这种颜色是因为DataSourceProperties.class下没有这些属性,
    # 并不能绑定到数据库的配置里
    # 但DruidDataSource.java中有这些属性
    # 想要生效, 自己配置, config.DruidConfig
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

想要配置生效,导入druid数据源

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }

    // 配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");// 默认就是允许所有访问
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }

    // 2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*"); // 排除拦截

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

在之前写的SpringinitializrApplicationTests类的testJDBC()方法中

System.out.println(dataSource.getClass());

语句打上断点,debug测试方法,查看控制台:

druid config

3、整合MyBatis

同样在Maven公共库中搜索MyBatis Spring Boot Starter,找到其Maven依赖

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.3.5</version>
</dependency>

3.1 MyBatis-Spring-Boot-Starter 简介

MyBatis-Spring-Boot-Starter类似一个中间件,链接Spring Boot和MyBatis,构建基于Spring Boot的MyBatis应用程序。

MyBatis-Spring-Boot-Starter 当前版本是 2.1.3,发布于2020年6月

MyBatis-Spring-Boot-Starter是个集成包,因此对MyBatis、MyBatis-Spring和SpringBoot的jar包都存在依赖,如下所示:

MyBatis-Spring-Boot-StarterMyBatis-SpringSpring BootJava
2.12.0 (need 2.0.2+ for enable all features)2.1 or higher8 or higher
1.31.31.56 or higher

3.2 分析依赖

mybatis

依赖会引入spring-boot-starter-jdbcmybatis的jar包,mybatis-spring中间整合包以及mybatis-spring-boot-autoconfigure自动配置包。

3.3 使用步骤

  • 配置数据源相关属性
  • 给数据库建表
  • 创建JavaBean
  • 注解版

3.4 注解版

// DepartmentMapper.java
// 指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {

    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    /*
    useGeneratedKeys = true: 使用自动生成的主键
    keyProperty = "id": 指明主键字段, id属性式用来封装主键的
    插入的department后, 主键会重新封装进来, 才会有值
     */
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);

}

访问方式:

  • 插入:http://localhost:8088/dept?departmentName=AA

insert department

  • 查询:http://localhost:8088/dept/1

问题:自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;

// MyBatisConfig.java
// 由于上面的org.apache.ibatis.session.Configuration, 所以这里使用全类名
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    /* 使用注解版MyBatis时, 本来数据库department表中字段是departmentName,
    如果将其改为department_name后, 就取不到值了, 如果不使用注解版, 可以直接在配置文件中配置驼峰命名规则,
    但现在只能使用配置类了
    */
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {
                // 开启驼峰命名法规则
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

还有,当我们实体类增多,每个映射文件都需要@Mapper注解?可以在启动类中使用MapperScan批量扫描所有的Mapper接口;

点击MapperScan查看源码:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({MapperScannerRegistrar.class})
public @interface MapperScan {
    String[] value() default {};

    String[] basePackages() default {};

    Class<?>[] basePackageClasses() default {};

    Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

    Class<? extends Annotation> annotationClass() default Annotation.class;

    Class<?> markerInterface() default Class.class;

    String sqlSessionTemplateRef() default "";

    String sqlSessionFactoryRef() default "";

    Class<? extends MapperFactoryBean> factoryBean() default MapperFactoryBean.class;
}

里面可以配置basePackages()参数:

@MapperScan("com.initializr.mapper")
@SpringBootApplication
public class SpringinitializrApplication {

  public static void main(String[] args) {
    System.out.println("Start...");
    SpringApplication.run(SpringinitializrApplication.class, args);
    System.out.println("Success...");
  }
  ...
}

3.5 配置文件版

MyBatis代码都托管到了GitHub,去GitHub查看配置文件写法,官方文档

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

使配置文件生效:

# application.yml
mybatis:
  # 指定全局配置文件的位置
  config-location: classpath:mybatis/mybatis-config.xml
  # 指定sql映射文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml

更多使用参照官方文档

4、整合SpringData的JPA模块

4.1 SpringData简介

SpringData官方文档

Spring Data项目的目的是为了简化构建基于Spring框架应用的数据访问技术,包括非关系数据库、Map-Reduce框架、云数据服务等等;另外一位包含对关系数据库的访问支持。

  • Spring Data包含多个子项目:

  • Spring Data特点

    SpringData为我们提供使用统一的API来对数据访问层进行操作;这主要是 Spring Data Commons项目来实现的。Spring Data Commons让我们在使用关系型或者非关系型数据访问技术时都基于Spring提供的统一标准,标准包含了CRUD(创建、获取、更新、删除)、査询、排序和分页的相关操作。

  • 统一的Repository接口

    • Repository<T, ID extends Serializable>:统一接口
    • RevisionRepository<T, ID extends Serializable, N extends Number& Comparable<N>>:基于乐观锁机制
    • CrudRepository<T, ID extends Serializable>:基本CRUD操作
    • PagingAndSortingRepository<T, ID extends Serializable>:基本CRUD及分页
  • 提供数据访问模板类xxxTemplate

    • 如:MongoTemplate、RedisTemplate等
  • JPA (Java Persistence API,Java持久层API) 与Spring Data

    • JpaRepository基本功能
    • 定义符合规范的方法命名
    • @Query自定义查询,定制查询SQL
    • Specification查询(Spring Data JPA支持JPA2.0的Criteria查询)
JPA

应用面向Spring Data编程,使用其提供模板。

4.2 整合SpringData JPA

引入启动器:

<!-- 引入JPA -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

查看视图:

starter-data-jpa
  • 可以看出,其导入了很多Spring业务功能模块,比如AOP和事务(Spring-tx)等;
  • 还可以看出其底层是用hibernate实现的,其中使用hibernate-entitymanager管理hibernate-jpa-*-ap,进行操作。

依然需要配置数据源,用JPA操作数据库。

JPA:ORM(Object Relational Mapping);

  • 编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和哪个数据表对应;如果省略默认表名就是user;
public class User {

  @Id //这是一个主键
  @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
  private Integer id;

  @Column(name = "last_name",length = 50) //这是和数据表对应的一个列
  private String lastName;
  @Column //省略默认列名就是属性名
  private String email;
  
  // getter and setter
}
  • 编写一个Dao接口来操作实体类对应的数据表(称为Repository)
//继承JpaRepository来完成对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer> {
}
  • 基本的配置JpaProperties
spring:  
 jpa:
    hibernate:
      # 更新或者创建数据表结构
      ddl-auto: update
      # 控制台显示SQL
    show-sql: true
  • 编写controller类
// UserController.java
@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id){
        User user = userRepository.findOne(id);
        return user;
    }

    @GetMapping("/user")
    public User insertUser(User user){
        // 有自增组件
        User save = userRepository.save(user);
        return save;
    }
}

写了两个简单的方法用来做测验

  • 启动主程序查看控制台:

    JPA-table-not-found

    可以看出,我们的配置ddl-auto: update生效了,当我们第一次启动项目,数据库中没有user表时,项目会自动为我们创建的。

    然后依次访问:http://localhost:8088/user/1

    和http://localhost:8088/user?lastName=Tom&email=tom@vip.com

    JPA-test

    查看控制台:

    JPA-console

    最后返回数据库是由数据的。

测试成功啦!

5、更多精彩

更多精彩,访问我的个人博客吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值