SpringBoot(三)-SpringData

一、dataSource

1、jdbc依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

2、yaml配置数据源

spring:
  datasource:
    username: xxx
    password: xxx
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.91.128:3306/jdbc

3、Test注入测试

 	@Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws Exception{
        System.out.println(dataSource.getClass());
        Connection connection = null;

            connection = dataSource.getConnection();
            System.out.println(connection);
            connection.close();
            
    }
class com.zaxxer.hikari.HikariDataSource
HikariProxyConnection@884599555 wrapping com.mysql.cj.jdbc.ConnectionImpl@43fda8d9

boot2默认Hikari

4、解析

  1. 数据源的配置相关在DataSourceProperties类里
  2. 通过DataSourceConfiguration发现:
支持
spring.datasource.tomcat、
spring.datasource.hikari、
spring.datasource.dbcp2、
spring.datasource.oracleucp
数据源
同时可以通过spring.datasource.type使用自定义数据源

5、通过springboot实现建表

spring.datasource.schema指定sql文件

spring: 
	datasource:
		 schema:
     		 - classpath:sql/department.sql
     		 - classpath:sql/employee.sql
    	 initialization-mode: ALWAYS

运行springboot程序,表就建好了
但是运行后要立马注释,因为第二次运行又会初始化表

二、整合druid

1、添加依赖

 		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.22</version>
        </dependency>

2、配置

spring.datasource.type指定数据源

spring:
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.91.128:3306/jdbc
    type: com.alibaba.druid.pool.DruidDataSource
    #   数据源其他配置
    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,log4j2
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

注意:filters: stat,wall,log4j2
boot1写的是log4j,但是boot要写log4j2,否则缺少log4j依赖会报错

在这里插入图片描述

经过debug你会发现,其他配置根本没有生效,因为当前dataSource还是DataSourceProperties的属性,所以需要自己配置

3、注入容器

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource(){
        return new DruidDataSource();
    }
    //配置druid的监控日志
    //1.管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParms=new HashMap<>();
        initParms.put("loginUsername","admin");
        initParms.put("loginPassword","12345");
        //运行localhost访问
//        initParms.put("allow","localhost");
        initParms.put("allow","");//不写就是运行所有访问
        initParms.put("deny","192.168.91.128");//拒绝访问
        return bean;
    }
    //2.配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String,String> initParms=new HashMap<>();
        initParms.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParms);
        bean.setUrlPatterns(Arrays.asList("/*"));//拦截所有请求
        return bean;
    }
}

就可以注入正确的dataSource
并且通过/druid请求监控日志

三、整合Mybatis

1、添加依赖

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

2、使用@Mapper注解编写mapper

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

    @Insert("insert into department(departmentName) values(departmentName)")
    int insertDept(Department department);

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

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

如果有多个mapper的话这样一个个使用@mapper就太麻烦了
在主程序里添加mapper扫描

@MapperScan(value = "com.chime.mapper")
@SpringBootApplication
public class Springboot06DataMybatisApplication {

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

}

3、Controller测试

@RestController
public class DeptController {
    @Autowired
    DepartmentMapper departmentMapper;

    @RequestMapping("/query")
    public Department query(Integer id){
        return departmentMapper.getDeptById(id);
    }

    @RequestMapping("/insert")
    public Department insert(Department department){
        departmentMapper.insertDept(department);
        return department;
    }
}

i通过nsert?departmentName=qwe请求发现,虽然插入成功,但是返回json显示id为空,可增加以下注解

	               是否使用自增主键,对应的属性
	@Options(useGeneratedKeys = true,keyProperty ="id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    int insertDept(Department department);

4、开启驼峰命名

Mybatis的ConfigurationCustomizer定制器就可以配置

@Configuration
public class MybatisConfig {
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
               configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

5、配置文件使用

(1)编写mybatis配置文件和mapper映射文件

在这里插入图片描述

(2)yaml配置指定配置文件路径
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值