今更、ではあるがメモ。
SpringBoot Ver 2.3.1
mybatis-spring-boot-starter は、Ver 2.1.3
コードの読みやすさの為に、lombok を使うことにして、
build.gradle の設定は、、
dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' implementation 'org.springframework.boot:spring-boot-starter-jdbc' implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3' implementation 'mysql:mysql-connector-java:8.0.21' implementation 'com.zaxxer:HikariCP:3.4.5' compileOnly('org.projectlombok:lombok') runtimeOnly 'mysql:mysql-connector-java' }
DB接続プールは、HikariCP である。
application.yml の記述
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: "jdbc:mysql://127.0.0.1:3306/sampleDB?serverTimezone=JST" username: root password: pass type: com.zaxxer.hikari.HikariDataSource hikari: minimum-idle: 4 maximum-pool-size: 10
SqlSessionFactory を生成する為に以下を用意しておけば良いだろう。
@MapperScan で、SQLMap マッパー interface を置くベースパッケージを宣言、
setMapUnderscoreToCamelCase(true) で、SnakeケースからCAMELケースへの自動変換を設定
import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import lombok.extern.slf4j.Slf4j; /** * DataBaseConfiguration */ @Configuration @MapperScan(basePackages = { "aaa.bbb.ccc" }) @Slf4j public class DataBaseConfiguration { @Autowired private DataSource dataSource; @Bean public SqlSessionFactory getSqlSessionFactory() { try{ SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); SqlSessionFactory factory = bean.getObject(); factory.getConfiguration().setMapUnderscoreToCamelCase(true); return factory; }catch(Exception e){ log.error(e.getMessage(), e); } return null; } }
あとは。。
@Autowired private SqlSessionFactory sqlSessionFactory;
SqlSession session = sqlSessionFactory.openSession();