对于数据访问层,无论是SQL还是NOSQL,SpringBoot默认采用整合Spring Data的方式进行统一处理,添加大量自动配置,屏蔽了很多设置。引入各种xxxTemplate,xxxRepository来简化我们对数据访问层的操作。对我们来说只需要进行简单的设置即可。我们将在数据访问章节测试使用SQL相关NOSQL在缓存、消息、检索等章节测试。
<dependency>
<groupId>org.springframework.bootgroupid>
<artifactId>spring-boot-starter-jdbcartifactid>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-jartifactid>
<scope>runtimescope>
dependency>
spring:
datasource:
username: root
password: 123456
url: jdbc:mysq1://192.168.15.22:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
效果:
默认是用org.apache.tomcatjdbcpoolDataSource作为数据源;
数据源的相关配置都在DataSourceProperties里面;
DataSourcelnitializer:ApplicationListener;
作用:
默认只需要将文件命名为:
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.8version>
dependency>
spring:
datasource:
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,去掉后监控界面sgl无法统计,"wall"用于防火墙
filters:stat,wall,log4j
maxPoo1PreparedStatementPerConnectionSize:20
useGlobalDataSourceStat: true
connectionProperties:druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
// 配置类
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix ="spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean =
new ServletRegistrationBean(new StatViewServlet(),"/druid/**")
Map<String,String> initParams=new HashMap<>(();
initParams.put("loginUsername" "admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean=newFilterRegistrationBean()
bean.setFilter(new WebstatFilter(());
Map<String,String> initParams=new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*")
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.3.1version>
dependency>
在mapper层的接口上添加注解
mybatis:
# 指定全局配置文件的位置
config-location:classpath:mybatis/mybatis-config.xml
# 指定sql映射文件的位置
mapper-locations:classpath:mybatis/mapper/*.xml
1、引入spring-boot-starter-data-jpa
2、配置文件打印SQL语句
3、创建Entity标注JPA注解
4、创建Repository接口继承JpaRepository
5、测试方法