六、SpringBoot与数据访问

一、JDBC

  1. 导入依赖
 <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>
  1. 配置数据源连接
spring:
  datasource:
    username: root
    password: 199902
    url: jdbc:mysql://hadoop102:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
  1. 效果:
    • 默认使用com.zaxxer.hikari.HikariDataSource数据源;
    • 数据源相关配置都在DataSourceProperties里面;
  2. 自动配置原理:
    org.springframework.boot.autoconfigure.jdbc:
    • 参考DataSourceConfiguration,根据配置创建数据源,默认使用Hikari连接池,可以使用spring.datasource.type指定自定义的数据源类型;
    • SpringBoot默认支持:
      org.apache.tomcat.jdbc.pool.DataSource
      org.apache.commons.dbcp2.BasicDataSource
      com.zaxxer.hikari.HikariDataSource
      oracle.ucp.jdbc.PoolDataSource
      
    • 自定义数据源
      @Configuration(
          proxyBeanMethods = false
      )
      @ConditionalOnMissingBean({DataSource.class})
      @ConditionalOnProperty(
          name = {"spring.datasource.type"}
      )
      static class Generic {
          Generic() {
          }
          @Bean
          DataSource dataSource(DataSourceProperties properties) {
          	//使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
              return properties.initializeDataSourceBuilder().build();
          }
      }
      
    • DataSourceInitializationConfiguration
      作用
      • ddlOnlyScriptDataSourceInitializer:运行建表语句
      • dmlOnlyScriptDataSourceInitializer:运行插入数据的SQL语句
        默认只需要将文件命名为:
      #执行ddl语句
      schema-*.sql、schema.sql
      #执行dml语句
      data-*.sql、data.sql
      #可以使用:
      spring:
        datasource:
          username: root
          password: 199902
          url: jdbc:mysql://hadoop102:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
          driver-class-name: com.mysql.jdbc.Driver
        sql:
          init:
            schema-locations:
              - classpath:schema.sql
            password: 199902
            username: root
            mode: always
      
    • 操作数据库:自动配置了JdbcTemplate操作数据库;

二、整合Druid数据源

  1. 导入依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<!-- 阿里官方的druid数据源jar包,适合在非springboot项目中使用,具体配置方法不做介绍-->
<!--
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.8</version>
</dependency>
-->
 <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
 <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid-spring-boot-starter</artifactId>
     <version>1.2.8</version>
 </dependency>
  1. 编写配置文件
spring:
  datasource:
    username: root
    password: 199902
    url: jdbc:mysql://hadoop102:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 5
      min-idle: 5
      max-active: 20
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 30000
      validation-query: select * from dual
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      #配置监控统计拦截的filters,去掉后监控界面SQL无法统计,·wall·用于防火墙
      filters: stat,wall
      max-pool-prepared-statement-per-connection-size: 20
      use-global-data-source-stat: true
      connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      stat-view-servlet:
        login-password: 123456
        login-username: admin
        enabled: true
        deny: 192.168.215.165
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions:
          - '*.js'
          - '*.css'
          - '/druid/*'
  1. 登录效果:
    在这里插入图片描述
    在这里插入图片描述

三、整合MyBatis

1.引入mybatis-starter依赖

 <dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>2.2.2</version>
 </dependency>

依赖关系图:
在这里插入图片描述

2. 步骤:

  • 配置数据源相关属性(见上一节Druid)
  • 给数据库建表
  • 创建javaBean

3、注解版

@Mapper
public interface DepartmentMapper{

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

    @Delete("delete from test.department where id = #{id}")
    int deleteDeptById(Integer id);
 	@Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into test.department (departmentName) values (#{departmentname}) ")
    int insertDept(Department department);

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

自定义mybatis的配置规则,给容器中添加ConfigurationCustomizer 组件;

@org.springframework.context.annotation.Configuration
public class MybatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

使用MapperScan批量扫描所有的mapper接口

@MapperScan(basePackages = "cn.hymll.springboot.mapper")
@SpringBootApplication
public class SpringbootDataMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootDataMybatisApplication.class, args);
    }

}

4、配置文件版

mybatis:
  #配置mybatis的配置文件路径
  config-location: classpath:mybatis-config.xml
  #配置mybatis的mapper映射文件路径
  mapper-locations: classpath:mapper/*

四、整合SpringData JPA

1、SpringData简介

在这里插入图片描述

2、整合SpringData JPA

JPA:ORM(object relational mapping)

  1. 编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
//配置JPA注解配置映射关系
//告诉JPA这是一个实体类
@Entity
//@Table来指定和那个数据表对应,如果省略,默认表名就是user
@Table(name = "tbl_user")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer"})
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
    private Integer id;
    @Column(name = "last_name",length = 50)//这是和数据表对应的一个列
    private String lastName;
    @Column()//省略默认列名就是属性名
    private String email;
    
	//setter and getter
}
  1. 编写一个DAO接口开操作实体类对应的数据表(Repository)
//继承JpaRepository来完成对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer> {
}
  1. 基本的配置(JpaProperties)
spring:
  jpa:
    hibernate:
      #更新或者创建数据表结构
      ddl-auto: update
    # 控制台显示SQL
    show-sql: true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天使吻过的BUG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值