Skip to content

Instantly share code, notes, and snippets.

@seraphy
Created July 17, 2019 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seraphy/32267b5b884c7a058417ce8adb41fef1 to your computer and use it in GitHub Desktop.
Save seraphy/32267b5b884c7a058417ce8adb41fef1 to your computer and use it in GitHub Desktop.
MyBatisの設定をプログラム上から行う実装例。Spring-Bootのuber-jarの場合は明示的にPathMatchingResourcePatternResolverでmapping.xmlを探索してマッピングする必要がある。
private SqlSessionFactory createFactory() {
DataSource dataSource = getDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("production", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
// configuration.addMappers("jp.seraphyware.example.dao.mapper");
// ↑ Spring-BootのUber-jarの場合では、この方法ではスキャンできない
try {
// uber-jar上でマッピングxmlをスキャンして明示的に設定を行う
Resource[] resources = new PathMatchingResourcePatternResolver()
.getResources("classpath:jp/seraphyware/example/dao/mapper/*.xml");
for (Resource resource : resources) {
logger.info("--> parse mapping-xml: {}", resource);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(),
configuration, resource.toString(), configuration.getSqlFragments());
xmlMapperBuilder.parse();
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return new SqlSessionFactoryBuilder().build(configuration);
}
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment