SpringBoot从入门到放弃,第四章,整合JDBC Druid Mybatis

SpringBoot从入门到放弃,第四章

一、springboot整合JDBC和DRUID

1、POM

<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>

2、application.yml

server:
  port: 8080
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver

3、jdbcTemplate

@RestController
public class HelloJdbcController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/jdbcData")
    public List jdbcData(){
        return jdbcTemplate.queryForList("select * from student");
    }
}

4、结果

[{"id":1,"stuname":"s1","classid":1},{"id":2,"stuname":"s2","classid":1},
{"id":3,"stuname":"s3","classid":1},{"id":4,"stuname":"s4","classid":2},
{"id":5,"stuname":"s5","classid":3},{"id":6,"stuname":"s6","classid":3}]

5、源码解读

位置:org.springframework.boot:spring-boot-autoconfigure:2.2.1.RELEASE包下的JDBC

DataSource注入

DataSourceConfiguration给容器导入数据源的

abstract class DataSourceConfiguration {
    
    protected static <T> T createDataSource(DataSourceProperties properties, Class<? extends DataSource> type) {
		return (T) properties.initializeDataSourceBuilder().type(type).build();
	}
    
    	@Configuration(proxyBeanMethods = false)
	@ConditionalOnClass(HikariDataSource.class)
	@ConditionalOnMissingBean(DataSource.class)
	@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.zaxxer.hikari.HikariDataSource",
			matchIfMissing = true)
	static class Hikari {

		@Bean
		@ConfigurationProperties(prefix = "spring.datasource.hikari")
		HikariDataSource dataSource(DataSourceProperties properties) {
			HikariDataSource dataSource = createDataSource(properties, HikariDataSource.class);
			if (StringUtils.hasText(properties.getName())) {
				dataSource.setPoolName(properties.getName());
			}
			return dataSource;
		}

	}
    
    ....
    
}

以上我们可以看出:如果我们将spring.datasource.type配置成com.alibaba.druid.pool.DruidDataSource并将相关的druid包导入,也可以更换数据源

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

DataSourceProperties将application中的配置信息注入数据源的

@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean{
    
    private String url;
	private String username;
	private String password;
    private String driverClassName;
    private List<String> schema;
    ....
        
    public DataSourceBuilder<?> initializeDataSourceBuilder() {
		return DataSourceBuilder.create(getClassLoader()).type(getType()).driverClassName(determineDriverClassName())
				.url(determineUrl()).username(determineUsername()).password(determinePassword());
	}
    
}

我们可以在YML中配置自动建表语句:

spring:
	datasource:
		schema:
            - classpath:user.sql
            - classpath:order.sql 

自动配置源码如下:

boolean createSchema() {
		List<Resource> scripts = getScripts("spring.datasource.schema", this.properties.getSchema(), "schema");
		if (!scripts.isEmpty()) {
			if (!isEnabled()) {
				logger.debug("Initialization disabled (not running DDL scripts)");
				return false;
			}
			String username = this.properties.getSchemaUsername();
			String password = this.properties.getSchemaPassword();
			runScripts(scripts, username, password);
		}
		return !scripts.isEmpty();
	}

6、整合DRUID

pom

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

YML

server:
  port: 8080
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 8
      min-idle: 1
      max-active: 20
      max-wait: 60000
      time-between-eviction-runsMillis: 60000
      min-evictable-idle-timeMillis: 300000
      validation-query: select 'x' FROM DUAL
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-open-prepared-statements: 20
      max-pool-prepared-statement-per-connection-size: 20
      filters: stat
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      use-global-data-source-stat: true

也可以增加如下内容:
#监控配置
# WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
spring.datasource.druid.web-stat-filter.enabled= #是否启用StatFilter默认值true
spring.datasource.druid.web-stat-filter.url-pattern=
spring.datasource.druid.web-stat-filter.exclusions=
spring.datasource.druid.web-stat-filter.session-stat-enable=
spring.datasource.druid.web-stat-filter.session-stat-max-count=
spring.datasource.druid.web-stat-filter.principal-session-name=
spring.datasource.druid.web-stat-filter.principal-cookie-name=
spring.datasource.druid.web-stat-filter.profile-enable=
 
# StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
spring.datasource.druid.stat-view-servlet.enabled= #是否启用StatViewServlet默认值true
spring.datasource.druid.stat-view-servlet.url-pattern=
spring.datasource.druid.stat-view-servlet.reset-enable=
spring.datasource.druid.stat-view-servlet.login-username=
spring.datasource.druid.stat-view-servlet.login-password=
spring.datasource.druid.stat-view-servlet.allow=
spring.datasource.druid.stat-view-servlet.deny=

启动类APP

@SpringBootApplication
public class BootJdbcApplication {

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

访问:

http://localhost:8080/druid
在这里插入图片描述

注意:如果引入的不是druid-spring-boot-starter而是如下

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

YML中的一些列 参数是无法自动加入到DruidDataSource中的,我们需要在配置文件中增加代码,如下:

@Bean
@ConfigurationProperties(prefix = "spring.datasource")//会将spring.datasoruce下的参数自动注入到DruidDataSource的上
public DataSource getDataSource() {
	return new DruidDataSource();
}

YML去掉DRUID

server:
  port: 8080
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    initial-size: 8
    min-idle: 1
    max-active: 20
    max-wait: 60000
    time-between-eviction-runsMillis: 60000
    min-evictable-idle-timeMillis: 300000
    validation-query: select 'x' FROM DUAL
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    pool-prepared-statements: true
    max-open-prepared-statements: 20
    max-pool-prepared-statement-per-connection-size: 20
    filters: stat
    connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    use-global-data-source-stat: true

因为在druid-spring-boot-starter中的配置源码是这样的:

@ConfigurationProperties("spring.datasource.druid")
public class DruidStatProperties {
    
}

且在启动类中增加

@Bean
public ServletRegistrationBean druidStatViewServlet() {
    //ServletRegistrationBean提供类的进行注册
    ServletRegistrationBean servletRegistrationBean =
        new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    //添加初始化参数:initParams
    //白名单:
    servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
    //IP黑名单(同时存在时,deny优先于allow)
    //如果满足deny,就提示:sorry,you are not permitted to view this page
    servletRegistrationBean.addInitParameter("deny", "192.168.1.73");
    //登录查看信息的账号和密码
    servletRegistrationBean.addInitParameter("loginUsername", "admin");
    servletRegistrationBean.addInitParameter("loginPassword", "123456");
    servletRegistrationBean.addInitParameter("resetEnable", "false");
    return servletRegistrationBean;
}


@Bean
public FilterRegistrationBean druidStatFilter() {
    FilterRegistrationBean filterRegistrationBean =
        new FilterRegistrationBean(new WebStatFilter());
    //添加过滤规则
    filterRegistrationBean.addUrlPatterns("/*");
    //添加需要忽略的格式信息
    filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif," +
                                            "*.jpg,*.png, *.css,*.ico,/druid/*");
    return filterRegistrationBean;

}

二、SpringBoot整合Mybatis

1、POM

![7](C:\Users\Administrator\Desktop\电商设计\images\7.png)<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>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>


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

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

我们查看一下mybatis的jar包依赖关系
在这里插入图片描述

2、entity

@Data
@ToString
public class Student {

    private Integer id;

    private String stuName;

    private Integer classId;
}

3、mapper

//或者在启动类上直接增加@MapperScan扫描包-->推荐@MapperScan
@Mapper
public interface StudentMapper {

    List<Student> findAll();

}

4、Controller

@RestController
public class HelloJdbcController {

    @Autowired
    private StudentMapper studentMapper;

    @GetMapping("/findAll")
    public List<Student> findAllStudent(){
        return studentMapper.findAll();
    }
}

5、Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lee.bootjdbc.mapper.StudentMapper">

    <select id="findAll" resultType="com.lee.bootjdbc.entity.Student">
      select * from student
    </select>

</mapper>

6、mybatis-config.xml全局配置

<?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>

7、application.yml

server:
  port: 8080
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 8
      min-idle: 1
      max-active: 20
      max-wait: 60000
      time-between-eviction-runsMillis: 60000
      min-evictable-idle-timeMillis: 300000
      validation-query: select 'x' FROM DUAL
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-open-prepared-statements: 20
      max-pool-prepared-statement-per-connection-size: 20
      filters: stat
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      use-global-data-source-stat: true

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

8、访问测试

http://localhost:8080/findAll

结果:
[{"id":1,"stuName":"s1","classId":1},{"id":2,"stuName":"s2","classId":1},
{"id":3,"stuName":"s3","classId":1},{"id":4,"stuName":"s4","classId":2},
{"id":5,"stuName":"s5","classId":3},{"id":6,"stuName":"s6","classId":3}]

9、源码解析

在org.mybatis.spring.boot:mybatis-spring-boot-autoconfigure:1.3.1中autoconfigure包下

MybatisAutoConfiguration

这里为mybatis注入了sqlSessionFactory,自动加载了配置信息等

@Configuration@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})@ConditionalOnBean({DataSource.class})@EnableConfigurationProperties({MybatisProperties.class})@AutoConfigureAfter({DataSourceAutoConfiguration.class})public class MybatisAutoConfiguration {
    
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource){
        ...
    }
    
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        ...
    }
    
    public static class AutoConfiguredMapperScannerRegistrar{

    }
    
     public void setBeanFactory(BeanFactory beanFactory){
            this.beanFactory = beanFactory;
     }
    
}

这里会加载application中mybatis的配置信息,且以mybatis开始

@ConfigurationProperties( prefix = "mybatis")
public class MybatisProperties {
    public static final String MYBATIS_PREFIX = "mybatis";
    private String configLocation;
    private String[] mapperLocations;
    private String typeAliasesPackage;
    private String typeHandlersPackage;
    private boolean checkConfigLocation = false;
    private ExecutorType executorType;
    private Properties configurationProperties;
    
 	...   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值