此方法为极简配置,支持mysql数据库多库连接、支持hikari连接池、支持mybatis(包括dao类和xml文件位置的配置)。
1、pom.xml中引入依赖:
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1
org.apache.tomcat
tomcat-jdbc
com.zaxxer
hikaricp
mysql
mysql-connector-java
我们使用了mybatis-spring-boot-starter,并让它把tomcat-jdbc连接池排除掉,这样spring-boot就会寻找是否有hikaricp可用,第二个依赖就被找到了,然后mysql-connector也有了。
2、application.yml中的相关配置:
spring:
profiles:
active: dev
datasource:
driver-class-name: com.mysql.jdbc.driver
username: root
password: 123456
hikari:
maxlifetime: 1765000 #一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒以上
maximumpoolsize: 15 #连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count)
mybatis:
mapperlocations: classpath:mapper/*.xml
---
# 开发环境配置
spring:
profiles: dev
datasource:
url: jdbc:mysql://localhost:3306/
---
# 测试环境配置
spring:
profiles: test
datasource:
url: jdbc:mysql://192.168.0.12:3306/
---
# 生产环境配置
spring:
profiles: prod
datasource:
url: jdbc:mysql://192.168.0.13:3306/
其中,datasource.url最后面不跟dbname,这样就可以支持多个db的情况,使用的时候只需要在sql语句的table名前面里面指定db名字就行了。
3、dao接口代码:
package com.xjj.dao;
import org.apache.ibatis.annotations.mapper;
import org.apache.ibatis.annotations.select;
import com.xjj.entity.person;
@mapper
public interface persondao {
@select("select id, first_name as firstname, last_name as lastname, birth_date as birthdate, sex, phone_no as phoneno"
+ " from test.t_person where id=#{0};")
public person getpersonbyid(int id);
public int insertperson(person person);
public int updatepersonbyid(person person);
public int updatepersonbyphoneno(person person);
}
只需要用@mapper注解,就可以支持被mybatis找到,并支持在方法上面写sql语句。
4、xml文件:
在resources目录下创建mapper目录,然后创建xml文件如下:
insert into test.t_person(first_name,last_name,birth_date,sex,phone_no,update_dt)
values(#{firstname},#{lastname},#{birthdate},#{sex},#{phoneno},now())
update test.t_person set
first_name=#{firstname}, last_name=#{lastname}, birth_date=#{birthdate}, sex=#{sex}, phone_no=#{phoneno}
where id=#{id}
update test.t_person set
first_name=#{firstname}, last_name=#{lastname}, birth_date=#{birthdate}, sex=#{sex}
where phone_no=#{phoneno}
5、测试:
@test
public void dbtest() throws jsonprocessingexception{
person person2 = persondao.getpersonbyid(2);
logger.info("person no 2 is: {}", objectmapper.writevalueasstring(person2));
person2.setfirstname("八");
persondao.updatepersonbyid(person2);
person2 = persondao.getpersonbyid(2);
logger.info("person no 2 after update is: {}", objectmapper.writevalueasstring(person2));
assertthat(person2.getfirstname(), equalto("八"));
}
总结
以上所述是小编给大家介绍的spring boot配置mysql数据库连接、hikari连接池和mybatis的简单配置方法,希望对大家有所帮助
希望与广大网友互动??
点此进行留言吧!