I. 서론
사용은 springboot의 JDBC, MyBatis로, 스프링 데이터 및 기타 데이터 액세스와 결합 될 수있다
데이터 액세스 계층의 경우, 좋은 SQL NoSQL에, 통합 통합 된 방식으로 스프링 데이터 처리와 springBoot 기본인지, 자동 구성의 큰 숫자, 설정 많은 방패를 추가합니다.
다양한 xxxTemplate, xxxRepository는 데이터 액세스 계층에 대한 우리의 작업을 간소화합니다. 우리는 간단한 설정이 필요합니다.
둘째, JDBC의 통합
1), 종속성을 추가
<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) 구성 데이터 소스 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) 시험 결과
테스트에 다음 코드를 사용하여
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
내장 된 기본 데이터 소스, 히카리를 사용하여, 결과는 다음과 같다
class com.zaxxer.hikari.HikariDataSource
HikariProxyConnection@108209958 wrapping com.mysql.cj.jdbc.ConnectionImpl@474821de
관련 데이터 소스는 DataSourceProperties 배치.
자동 구성 4) 원리
org.springframework.boot.autoconfigure.jdbc
- DataSourceConfiguration 구성 데이터 소스에있어서, 기본 히카리 연결 풀을 생성하고, 데이터 소스 spring.datasource.type를 선택하는데 사용될 수있다.
//每个数据源上都有此注解,根据配置中的spring.datasource.type来配置数据源
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.zaxxer.hikari.HikariDataSource",
matchIfMissing = true)
static class Hikari {
- 기본 지원되는 데이터 소스
//tomcat
org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.Tomcat
//hikari
org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.Hikari
//Dbcp2
org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.Dbcp2
- 사용자 정의 데이터 소스
//自定义数据源,但制定的类型不为上面三种时,便通过此来创建自定义数据源
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {
@Bean
DataSource dataSource(DataSourceProperties properties) {
//使用反射创建响应数据的数据源,并且绑定相关属性
return properties.initializeDataSourceBuilder().build();
}
}
DataSourceInitializerInvoker : 만약 ApplicationListener 실현
당신은 SQL을 수행하는 데이터 소스를 만들 때 자동으로 수행 할 수 있습니다 역할
1) afterPropertiesSet. 테이블 문의 건설을 수행하려면
2) onApplicationEvent. 문 데이터 삽입을 수행하는 데 사용
/** * 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 指定位置
스프링 boot2.x를 들어, 자동으로 SQL 스크립트를 실행 내장 데이터 소스, 순서에 사용하지 않고 사용, 초기화 모드를 추가해야합니다 : 항상
//建表时是否执行DML和DDL脚本 public enum DataSourceInitializationMode { /** * Always initialize the datasource.总是会执行 */ ALWAYS, /** * Only initialize an embedded datasource.嵌入式会执行 */ EMBEDDED, /** * Do not initialize the datasource.不会执行 */ NEVER }
- 데이터베이스 작업은 : JdbcTemplateConfiguration 자동으로 데이터베이스와 NamedParameterJdbcTemplateConfiguration를 작동하도록 구성
드루이드의 5) 통합
데이터 소스를 만들고 1. 드루이드 속성이 할당 등
드루이드의 응용 프로그램 속성의 기본 구성. 사용 spring.datasource.type 지정된 데이터 소스의 드루이드
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
그러나 여기가 문제가 될, 그것은에 할당 된 DataSourceProperties 데이터 소스입니다 것입니다. 그러나 다른 데이터 소스 DataSourceProperties 구성 속성 클래스가 없습니다. 우리가 원하는 그래서 다른 구성은 데이터 소스의 생성에 존재하지 않습니다.
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
이 문제는 매우 간단 해결하기 위해 데이터 소스에 대한 자신의 할당, 직접 DruidDataSource 할당 된 다른 구성의 값입니다
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
}
오류 힘 실행 시간이 완료되면, 우리는 log4j에의 종속성을 추가해야합니다. 성공적를 실행할 수 있습니다
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2. 모니터링 구성 데이터 소스
- 서블릿의 구성 관리 배경
임베디드 서블릿 컨테이너는 서블릿 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;
}
셋째, 통합의 MyBatis
의존 가입
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
참고 버전의 MyBatis
@Mapper 전용 인터페이스에 주석을 추가 할 필요가 해당 주석 방법에 사용될 수있다. 대량을 추가하려면 주석이 용기에 모든 검색 패키지에 매퍼에 메인 프로그램에 @MapperScan (값 = "매퍼 패키지 이름을")을 사용할 수 있습니다 @Mapper.
@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);
}
그러나 몇 가지 질문이있을 수 있습니다, 우리는 설정하는 방법의 구성 파일에 설정했다? 이러한 개구 번째 레벨 캐시 방법을 사용하거나 camelCasing 같은로서
의 자동 구성 클래스 MyBatisAutoConfiguration의 MyBatis로, 당신은 SqlSessionFactory는를 만들 때, 당신은 클래스 구성에 얻을 것이다, 및 사용자 정의 방법 configurationCustomizers 클래스를 수행됩니다.
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);
}
}
우리는 컨테이너 configurationCustomizers에 추가 할 수 있도록 어셈블리 구성 파일과 동일한 구성을 달성하기 위해 내부 사용자 정의 방법을 다시 작성합니다. 예를 들면 : 열려있는 혹 명칭
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}