SpringBoot from getting started to giving up, Chapter 4, integrating JDBC Druid Mybatis

SpringBoot from getting started to giving up, Chapter 4

I. springboot integrates JDBC and 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, result

[{"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. Source code interpretation

Location: JDBC under org.springframework.boot: spring boot autoconfigure: 2.2.1.release package

DataSource injection

DataSourceConfiguration imports the

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

	}
    
    ....
    
}

We can see from the above: if we configure spring.datasource.type as com.alibaba.druid.pool.DruidDataSource and import the related Druid package, we can also replace the data source

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

DataSourceProperties injects the configuration information in the application into the

@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());
	}
    
}

We can configure automatic table creation statements in YML:

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

The automatic configuration source code is as follows:

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

//The following can also be added:
#Monitoring configuration
# For the configuration of WebStatFilter, please refer to the Druid Wiki, configuration, and configure WebStatFilter
spring.datasource.druid.web-stat-filter.enabled= #Enable StatFilter default value 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=
 
# For StatViewServlet configuration, please refer to Druid Wiki for instructions, and configure StatViewServlet configuration
spring.datasource.druid.stat-view-servlet.enabled= #Enable StatViewServlet default value 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=

Start class APP

@SpringBootApplication
public class BootJdbcApplication {

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

Visit:

http://localhost:8080/druid

Note: if Druid spring boot starter is not introduced, it is as follows

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

Some column parameters in YML cannot be automatically added to DruidDataSource. We need to add code to the configuration file as follows:

@Bean
@ConfigurationProperties(prefix = "spring.datasource")//The parameters under spring.datasource will be automatically injected into the DruidDataSource
public DataSource getDataSource() {
	return new DruidDataSource();
}

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

Because the configuration source code in Druid spring boot starter is as follows:

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

And added in the startup class

@Bean
public ServletRegistrationBean druidStatViewServlet() {
    //ServletRegistrationBean provides the registration of the class
    ServletRegistrationBean servletRegistrationBean =
        new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    //Add initialization parameter: initParams
    //White list:
    servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
    //IP blacklist (deny takes precedence over allow when it exists at the same time)
    //If deny is met, it will prompt: sorry, you are not allowed to view this page
    servletRegistrationBean.addInitParameter("deny", "192.168.1.73");
    //Account and password for logging in to view information
    servletRegistrationBean.addInitParameter("loginUsername", "admin");
    servletRegistrationBean.addInitParameter("loginPassword", "123456");
    servletRegistrationBean.addInitParameter("resetEnable", "false");
    return servletRegistrationBean;
}


@Bean
public FilterRegistrationBean druidStatFilter() {
    FilterRegistrationBean filterRegistrationBean =
        new FilterRegistrationBean(new WebStatFilter());
    //Add filter rule
    filterRegistrationBean.addUrlPatterns("/*");
    //Add formatting information to ignore
    filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif," +
                                            "*.jpg,*.png, *.css,*.ico,/druid/*");
    return filterRegistrationBean;

}

II. SpringBoot integrates Mybatis

1,POM

![7](C:\Users\Administrator\Desktop\Electronic business design\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>

Let's look at the jar package dependency of mybatis

2,entity

@Data
@ToString
public class Student {

    private Integer id;

    private String stuName;

    private Integer classId;
}

3,mapper

//Or directly add @ MapperScan scanning package on startup class -- > recommend @ 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. Global configuration of 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. Access test

http://localhost:8080/findAll

//Result:
[{"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. Source code analysis

Under the autoconfigure package in org.mybatis.spring.boot:mybatis-spring-boot-autoconfigure:1.3.1

MybatisAutoConfiguration

Here, sqlSessionFactory is injected into mybatis, and configuration information is loaded automatically

@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;
     }
    
}

The configuration information of mybatis in the application will be loaded here, and start with 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;
    
 	...   
}

Keywords: Programming Druid Spring Mybatis JDBC

Added by hthighway on Thu, 14 Nov 2019 16:41:21 +0200