Created
July 17, 2019 05:38
-
-
Save seraphy/32267b5b884c7a058417ce8adb41fef1 to your computer and use it in GitHub Desktop.
MyBatisの設定をプログラム上から行う実装例。Spring-Bootのuber-jarの場合は明示的にPathMatchingResourcePatternResolverでmapping.xmlを探索してマッピングする必要がある。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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