hikariCP,号称目前(2018.11)最快的数据库连接池,本文整理了一下spring boot整合mybatis和hikariCP的方法,以备后用。
spring boot 2.0以上版本默认hikariCP作为数据库连接池,本文整理的是spring boot2.0以下版本的整合方法。
1.demo代码整体架构
2.创建maven项目
3.修改pom.xml,添加依赖
org.springframework.boot
spring-boot-starter-parent
1.5.10.RELEASE
org.springframework.boot
spring-boot-starter-jdbc
org.apache.tomcat
tomcat-jdbc
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
com.zaxxer
HikariCP
compile
org.springframework.boot
spring-boot-starter-test
test
3.在resources文件下新建配置文件:application.properties
#tomcat prot
server.port=8080
#db
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mytest?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.default-auto-commit=true
spring.datasource.auto-commit=true
spring.datasource.maximum-pool-size=10
spring.datasource.max-idle=5
spring.datasource.max-wait=10000
spring.datasource.min-idle=2
spring.datasource.initial-size=3
#mybatis
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=cn.whg.demo.model
注意:需要根据自己的项目结构修改以上配置文件内容的引用内容。
4.创建dao处理接口,TestDao.java
@Mapper
public interface TestDao {
int testSelect();
}
5.创建service类,TestService.java
@Service
public class TestService {
@Autowired
private TestDao dao;
public int testSelect() {
return dao.testSelect();
}
}
6.创建controller类,TestController.java
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService service;
@GetMapping("getResult")
public void getResutl(){
int result = service.testSelect();
System.out.println("select result:"+result);
}
}
7.创建启动类,MyApplication.java
@SpringBootApplication
public class MyApplication {
/**
*
* 方法描述:启动入口 TODO
* 创建人: wanghonggang
* 创建时间: 2018年11月6日 下午5:28:54
* 修改记录:
* @param args
* void
*/
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(MyApplication.class, args);
DataSource dataSource = applicationContext.getBean(DataSource.class);
//连接池名称
System.out.println("datasource is :" + dataSource);
}
}
注意:启动类最好放到dao、service、controller类的上层,否则还需要进行其他处理。
8.在resources文件夹下创建mapper文件夹,并在mapper文件夹下创建DB映射test.xml
9.至此,代码完成,启动项目,访问 http://localhost:8080/test/getResult ,可以看到如下结果:
注意:以上代码,请勿忽略@注释。
完整代码下载地址:https://download.csdn.net/download/ssxueyi/10768701