SpringBoot集成mybatis(配置通用mapper)并且使用druid作为数据库连接池
程序员文章站
2022-07-15 10:54:40
...
主要包括:
- springBoot集成mybatis框架
- 使用配置mybatis框架的通用mapper功能
- 使用阿里的druid作为数据库连接池
- 利用swagger进行接口测试
一.先创建一个springBoot的maven工程,这个小伙伴肯定都会
二.引入相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<!--阿里连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- mybatis通用mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<!--分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<!-- API文档生成-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.0</version>
</dependency>
三.配置mybatis
@Configuration
public class MybatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factroy = new SqlSessionFactoryBean();
factroy.setDataSource(dataSource);
VFS.addImplClass(SpringBootVFS.class);
factroy.setTypeAliasesPackage("com.school.project.entity");
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
factroy.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
//配置分页插件
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("pageSizeZero", "true"); //分页尺寸为0时候查询所有记录不再执行分页
properties.setProperty("reasonable", "true"); //页码<=查询第一页 ,页码>=总页数查询最后一页
properties.setProperty("supportMethodsArguments", "true"); // 支持通过mapper接口参数传递分页参数
pageHelper.setProperties(properties);
//添加插件
factroy.setPlugins(new Interceptor[]{pageHelper});
try {
//开启驼峰命名转换
factroy.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return factroy.getObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
mapperScannerConfigurer.setBasePackage("com.school.project.dao.mapper"); //存放mapper接口的包路径
//配置通用mapper
Properties properties = new Properties();
properties.setProperty("mappers","com.school.project.dao.base.Mapper"); //mapper插件基础接口的全限定明 此包下的Mapper<T> 继承 BaseMapper<T>,ConditionMapper<T>,IdsMapper<T>,InsertListMapper<T> 接口,如需其他接口可以参考官方文档。
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}
}
四.开启swagger
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
.title("学生管理系统")
.build())
.select()
.apis(RequestHandlerSelectors.basePackage("com.school.project.controller"))
.paths(PathSelectors.any())
.build();
}
}
配置好这个在浏览器*问localhost:8899/student/swagger-ui.html 即可访问
五.配置文件里的一些配置
server:
port: 8899
servlet:
context-path: /student
spring:
profiles:
active: dev
jackson:
date-format: yyyy-MM-dd HH:mm:ss
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://192.168.109.66:3306/learn?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
type: com.alibaba.druid.pool.DruidDataSource
# 连接池配置
druid:
#启动程序时,在连接池中初始化多少个连接
initialSize: 5
#最小连接池数量
minIdle: 5
##连接池中最多支持多少个活动会话
maxActive: 20
# 获取连接时最大等待时间,单位毫秒
maxWait: 60000
# 有两个含义:
#1) Destroy线程会检测连接的间隔时间
# 2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明
timeBetweenEvictionRunsMillis: 60000
# Destory线程中如果检测到当前连接的最后活跃时间和当前时间的差值大于,minEvictableIdleTimeMillis,则关闭当前连接
minEvictableIdleTimeMillis: 300000
#用来检测连接是否有效的sql,要求是一个查询语句。
validationQuery: SELECT 1 FROM DUAL
#建议配置为true,不影响性能,并且保证安全性。
#申请连接的时候检测,如果空闲时间大于
#timeBetweenEvictionRunsMillis,
#执行validationQuery检测连接是否有效。
testWhileIde: true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会影响性能
testOnBorrow: false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会影响性能
testOnReturn: false
# 是否缓存preparedStatement,也就是PSCache mql5.5以上建议开启
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j2
maxPoolPreparedStatementPerConnectionSize: 20
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mvc:
view:
prefix: /jsp/
suffix: .jsp
jpa:
hibernate:
ddl-auto: update
logging:
level:
org.springframework: INFO
file: /home/student/student.log
jpa的配置到时候可以通过注解生成表,第一次ddl设置成create,以后改成update
六.druid的配置文件
@Configuration
public class DruidConfiguration {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDateSource(){
DruidDataSource druidDataSource =new DruidDataSource();
return druidDataSource;
}
//配置一个druid的监控
//配置一个后台的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 = new FilterRegistrationBean();
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;
}
启动类上加上
@ServletComponentScan注解
配置好后通过浏览器输入localhost:8899/student/druid就可访问druid的监控台
七.配置基础mapper
public interface Mapper<T> extends
BaseMapper<T>,
ConditionMapper<T>,
IdsMapper<T>,
InsertListMapper<T>
{
}
做完以上配置就可以写对应的entity、service、controller、启动项目进行测试使用了。
上一篇: 矩阵运算——矩阵乘除法python
下一篇: SAP Code 增强