标签:running this 数据访问层 自己 artifact under property star 响应
使用springboot可以与jdbc、mybatis、spring data等结合进行数据访问
对于数据访问层,无论是SQL好NoSQL,springBoot默认采用整合Spring Data的方式进行统一处理,添加大量自动配置,屏蔽了很多设置。
各种xxxTemplate,xxxRepository来简化我们对数据访问层的操作。对我们来说只需要进行简单的设置即可。
<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>
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
用下面代码测试
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
结果如下,使用的是默认的内置数据源,hikari
class com.zaxxer.hikari.HikariDataSource
HikariProxyConnection@108209958 wrapping com.mysql.cj.jdbc.ConnectionImpl@474821de
数据源相关配置都在DataSourceProperties中。
org.springframework.boot.autoconfigure.jdbc
//每个数据源上都有此注解,根据配置中的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
指定位置
对于spring-boot2.x,如果使用不使用内置的数据源,要想自动执行sql脚本,必须要加上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
}
在application中配置Druid的基本属性。使用spring.datasource.type指定数据源为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
不过这里会存在一个问题,那就是DataSource是通过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>
嵌入式servlet容器创建servlet是通过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;
}
加入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
只需要在接口上加入@Mapper注解,在方法上使用对应的注解即可。若要批量加上@Mapper注解,可在主程序上使用@MapperScan(value="mapper包名")来将包下的所有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);
}
但可能会有这样的疑问,我们原本在配置文件中的设置该怎样设置?比如开启二级缓存,使用驼峰命名法等
在mybatis的自动配置类MyBatisAutoConfiguration中,在创建SqlSessionFactory时,会获取到配置类,并且将configurationCustomizers类中的customize方法执行.
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组件,重写其内部的customize方法,以实现像配置文件一样的配置。例如:开启驼峰命名法
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
标签:running this 数据访问层 自己 artifact under property star 响应
原文地址:https://www.cnblogs.com/ylcc-zyq/p/12535592.html