トッカンソフトウェア

SpringBoot MyBatis② SQLを外部ファイル

今回はSpringBootのMyBatisで外部にあるSQL設定ファイルにアクセスします。
前回の続きからやるので先にそちらで環境を構築して下さい。


設定ファイル

application.properties

				
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=ps
mybatis.mapper-locations=classpath*:/mappers/*.xml
mybatis.configuration.map-underscore-to-camel-case=true

			
mybatis.mapper-locationsでSQLファイルの場所を指定します。
Spring用設定ファイルで設定したときのmapperLocationsと同じ指定になります。

mybatis.configuration.map-underscore-to-camel-caseはテーブルの項目がスネークケース、Javaの変数がキャメルケースの場合でもうまくマッピングしてくれます。
(今回の処理では関係ありません)

UserDao.xml

				
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="spring.test.UserDao">
	<select id="getUserList" resultType="map">
		select id,name from m_user
	</select>
</mapper>


			
戻り値にmapを指定すると、JavaのMapに検索結果を入れてくれます。

設定ファイル

UserDao.java

				
package spring.test;

import java.util.List;
import java.util.Map;

public interface UserDao {

	public List<Map<String, Object>> getUserList();
}


			

ファイル構成


実行

前回と同様にコンソールにテーブルのテーブルの内容が出力されます。






ページのトップへ戻る