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。table文の構築を実行するには
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);
}
};
}
}