I. Introduction
Use may be combined with springboot jdbc, mybatis, spring data and other data access
For data access layer, whether it is good SQL NoSQL, springBoot default with an integrated unified manner Spring Data processing, add a large number of automatic configuration, the shield a lot of settings.
Various xxxTemplate, xxxRepository to streamline our operations on the data access layer. For us need only a simple settings.
Second, the integration of JDBC
1), add dependencies
<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>
<version>${mysql-version}</version>
<scope>runtime</scope>
</dependency>
2), the configuration data source application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
3), the test results
Use the following code to test
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
The results are as follows, using the built-in default data source, Hikari
class com.zaxxer.hikari.HikariDataSource
HikariProxyConnection@108209958 wrapping com.mysql.cj.jdbc.ConnectionImpl@474821de
Related data source arranged in the DataSourceProperties.
4), the principle of automatic configuration
org.springframework.boot.autoconfigure.jdbc
- DataSourceConfiguration, according to the configuration data source is created, default hikari connection pool and may be used to select a data source spring.datasource.type.
//每个数据源上都有此注解,根据配置中的spring.datasource.type来配置数据源
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.zaxxer.hikari.HikariDataSource",
matchIfMissing = true)
static class Hikari {
- The default Supported data sources
//tomcat
org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.Tomcat
//hikari
org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.Hikari
//Dbcp2
org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.Dbcp2
- Custom Data Sources
//自定义数据源,但制定的类型不为上面三种时,便通过此来创建自定义数据源
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {
@Bean
DataSource dataSource(DataSourceProperties properties) {
//使用反射创建响应数据的数据源,并且绑定相关属性
return properties.initializeDataSourceBuilder().build();
}
}
DataSourceInitializerInvoker: realized ApplicationListener
It can be performed automatically when you create a data source to perform sql: Role
1), afterPropertiesSet. To perform the construction of the table statement
2), onApplicationEvent. Statement is used to perform data insertion
/** * Bean to handle {@link DataSource} initialization by running {@literal schema-*.sql} on * {@link InitializingBean#afterPropertiesSet()} and {@literal data-*.sql} SQL scripts on * a {@link DataSourceSchemaCreatedEvent}. */ 由官方注释可知,通过afterPropertiesSet方法,可以执行格式为schema-*.sql的语句进行建表操作,通过onApplicationEvent方法可以执行格式为data-*sql的插入操作 可以使用: schema: - classpath:xxx.sql 指定位置
For spring-boot2.x, if used without the use of built-in data source, in order to automatically execute sql script, must be added initialization-mode: always
//建表时是否执行DML和DDL脚本 public enum DataSourceInitializationMode { /** * Always initialize the datasource.总是会执行 */ ALWAYS, /** * Only initialize an embedded datasource.嵌入式会执行 */ EMBEDDED, /** * Do not initialize the datasource.不会执行 */ NEVER }
- Database operations: JdbcTemplateConfiguration automatically configured to operate the database and NamedParameterJdbcTemplateConfiguration
5) integration of Druid
1. Create a data source and as a Druid property assignment
The basic configuration of the application properties of the Druid. Use spring.datasource.type specified data source druid
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
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,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
But here there will be a problem, and that is by DataSourceProperties DataSource is assigned to. However, there is no other data sources DataSourceProperties configuration attribute class. So we want other configuration does not exist in the creation of the data source.
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
To solve this problem is very simple, is their assignment for the data source, the value of other configurations directly assigned DruidDataSource
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
}
Upon completion of the error might run time, then we need to add a dependency of log4j. Will be able to successfully execute the
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2. monitoring configuration data source
- Configuration management background of a Servlet
Embedded servlet container creates servlet be created by ServletRegistrationBean
/**
* 配置一个Web监控的servlet
* @return
*/
@Bean
public ServletRegistrationBean<StatViewServlet> statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
Map<String,String> initParameters = new HashMap<>(10);
initParameters.put("loginUsername","root");
initParameters.put("loginPassword","123456");
//默认允许所有访问
initParameters.put("allow","");
bean.setInitParameters(initParameters);
return bean;
}
/**
* 配置一个Web监控的Filter
* @return
*/
@Bean
public FilterRegistrationBean<WebStatFilter> webStatFilter(){
FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>();
Map<String,String> initParameters = new HashMap<>(10);
initParameters.put("exclusions","*.js,*css,/druid/*");
bean.setUrlPatterns(Collections.singletonList("/*"));
bean.setInitParameters(initParameters);
return bean;
}
Third, integration mybatis
Join dependence
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
Notes version mybatis
@Mapper only need to add annotations to the interface, can be used in the corresponding annotation method. To add bulk @Mapper annotations may be used @MapperScan (value = "mapper package name") on the main program to the mapper at all scan packages into the container.
@Mapper
public interface DepartmentMappper {
@Select("select * from department where id=#{id} ")
Department getDeptById(Integer id);
@Delete("delete from department where id=#{id}")
int deleteById(Integer id);
@Update("update department set departmentName=#{departmentName} where id=#{id} ")
int update(Department department);
@Options(useGeneratedKeys = true,keyProperty = "id")//自增主键
@Insert("insert into department(departmentName) values(#{departmentName} )")
int insert(Department department);
}
But may have some questions, we had set up in the configuration file of how to set up? Such as opening second-level cache, method or the like using camelCasing
In the automatic configuration class MyBatisAutoConfiguration mybatis in, when you create SqlSessionFactory, you will get to class configuration, and will be performed customize method configurationCustomizers class.
private void applyConfiguration(SqlSessionFactoryBean factory) {
org.apache.ibatis.session.Configuration configuration = this.properties.getConfiguration();
if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {
configuration = new org.apache.ibatis.session.Configuration();
}
if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {
Iterator var3 = this.configurationCustomizers.iterator();
while(var3.hasNext()) {
ConfigurationCustomizer customizer = (ConfigurationCustomizer)var3.next();
customizer.customize(configuration);
}
}
So we can add in the container configurationCustomizers assembly to rewrite its internal customize methods to achieve the same configuration as the configuration file. For example: open hump nomenclature
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}