Spring Boot에서 Mybatis를 적용하는 방법이다.
Spring MVC에서는 Mybatis를 적용하기 위해 DataSource에 Mybatis Configuration 파일과 Mapper Location을 정의해주어야 한다.
■context-datasource.xml
<beans profile="sqlite"> <!-- SQLIITE --> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="batchweb" /> <property name="resourceRef" value="true" /> </bean> </beans> <beans> <!-- SqlSession setup for MyBatis Database Layer --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:/sqlmap/config/mybatis-config.xml" /> <property name="mapperLocations"> <list> <value>classpath:/sqlmap/cmn/*SQL.xml</value> <value>classpath:/sqlmap/#{system['database.type']}/**/*SQL.xml</value> </list> </property> </bean> <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean>
<bean id="baseDao" class="batch.web.base.BaseDao"> <property name="sqlSessionFactory" ref="sqlSession" /> </bean> |
먼저 JndiObjectFactoryBean을 이용하여 dataSource bean을 설정한다.
다음으로 SqlSessionFactoryBean에 configLocation과 mapperLocations에 Mybatis configuration 파일 위치를 정의하고, mapperLocation에 Mybatis에서 사용하는 SQL 파일의 위치를 정의한다.
BaseDao를 사용하기 위해 bean으로 정의한다. 이때 BaseDao SqlSessionFactory를 sqlSession을 주입한다.
bean 설정이 완료된 후 DAO를 생성한다.
■ BaseDao.java
import org.mybatis.spring.support.SqlSessionDaoSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import batch.web.mybatis.JobParamResultHandler; public class BaseDao extends SqlSessionDaoSupport implements InitializingBean {
private static Logger LOGGER = LoggerFactory.getLogger(BaseDao.class);
/** * *<pre> * 1.Description: Insert Data * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param params * @return * @throws Exception */ public <T> int insert(String sqlId, T params) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return getSqlSession().insert(sqlId, params); }
/** * *<pre> * 1.Description: Update Data * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param params * @return * @throws Exception */ public <T> int update(String sqlId, T params) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return getSqlSession().update(sqlId, params); } /** * *<pre> * 1.Description: Delete Data * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param params * @return * @throws Exception */ public <T> int delete(String sqlId, T params) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return getSqlSession().delete(sqlId, params); } /** * *<pre> * 1.Description: Select data for one row * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param param * @return * @throws Exception */ public <T, V> T select(String sqlId, V param) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return getSqlSession().selectOne(sqlId, param); } /** * *<pre> * 1.Description: select data for one row without parameter * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @return * @throws Exception */ public <T, V> T select(String sqlId) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return getSqlSession().selectOne(sqlId); } /** * *<pre> * 1.Description: Select data list with parameter * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param param * @return * @throws Exception */ @SuppressWarnings("unchecked") public <T, V> T selectList(String sqlId, V param) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return (T) getSqlSession().selectList(sqlId, param); }
/** * *<pre> * 1.Description: Select list without parameter * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @return * @throws Exception */ @SuppressWarnings("unchecked") public <T, V> T selectList(String sqlId) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return (T) getSqlSession().selectList(sqlId); }
/** * *<pre> * 1.Description: Select data with Result Handler * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param job * @param handler * @throws Exception */ public <T> void selectListWithHandler(String sqlId, Object job, JobParamResultHandler<T> handler) throws Exception { getSqlSession().select(sqlId, job, handler); }
} |
Spring Boot에서는 sqlSessionFactory를 bean으로 정의한다.
■ DatasourceConfig.java
import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; @Configuration //@MapperScan(value ="dynm.demo.mapper1", sqlSessionFactoryRef="db1SqlSessionFactory") //@EnableTransactionManagement public class DatasourceConfig { @Bean(name="sqlSessionFactory") public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); Resource[] sqlResources = new PathMatchingResourcePatternResolver().getResources("classpath:sqlmap/**/*SQL.xml"); Resource configLocation = new PathMatchingResourcePatternResolver().getResource("classpath:sqlmap/config/mybatis-config.xml");
factoryBean.setConfigLocation(configLocation);
factoryBean.setMapperLocations(sqlResources); return factoryBean.getObject(); } @Bean(name="sqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); }
} |
SqlSesionFactroy를 bean으로 생성하기위해 SqlSessionFactoryBean을 생성한 후 configurationLocation과 mapperLocations을 정의한다.
BaseDao를 bean으로 사용하기 위해 다음과 같이 BaseDao를 개발한다.
■BaseDao.java
import javax.annotation.PostConstruct; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository("baseDao") public class BaseDao extends SqlSessionDaoSupport implements InitializingBean {
private static Logger LOGGER = LoggerFactory.getLogger(BaseDao.class);
@Autowired private SqlSessionFactory sqlSessionFactory;
/** * *<pre> * 1.Description: Insert Data * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param params * @return * @throws Exception */ public <T> int insert(String sqlId, T params) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return getSqlSession().insert(sqlId, params); }
/** * *<pre> * 1.Description: Update Data * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param params * @return * @throws Exception */ public <T> int update(String sqlId, T params) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return getSqlSession().update(sqlId, params); } /** * *<pre> * 1.Description: Delete Data * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param params * @return * @throws Exception */ public <T> int delete(String sqlId, T params) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return getSqlSession().delete(sqlId, params); } /** * *<pre> * 1.Description: Select data for one row * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param param * @return * @throws Exception */ public <T, V> T select(String sqlId, V param) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return getSqlSession().selectOne(sqlId, param); } /** * *<pre> * 1.Description: select data for one row without parameter * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @return * @throws Exception */ public <T, V> T select(String sqlId) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return getSqlSession().selectOne(sqlId); } /** * *<pre> * 1.Description: Select data list with parameter * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @param param * @return * @throws Exception */ @SuppressWarnings("unchecked") public <T, V> T selectList(String sqlId, V param) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return (T) getSqlSession().selectList(sqlId, param); }
/** * *<pre> * 1.Description: Select list without parameter * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @param sqlId * @return * @throws Exception */ @SuppressWarnings("unchecked") public <T, V> T selectList(String sqlId) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excuted SQL ID :: {}", sqlId); } return (T) getSqlSession().selectList(sqlId); }
/** * *<pre> * 1.Description: When using spring boot, SqlSessionFactory should be set in SqlSessionDaoSupport * If you use spring MVC, no need to set sqlsessionfactory, because baseDao should be set bean * 2.Biz Logic: * 3.Author : LGCNS *</pre> * @throws Exception */ @PostConstruct public void postConstruct() throws Exception { super.setSqlSessionFactory(sqlSessionFactory); } } |
먼저 BaseDao를 Repository Annotation을 이용하여 bean형식으로 로 정의한다.
여기서 BaseDao에 SqusessionFactory를 주입하기 위해 bean으로 정의한 SqlSessionFactory를 Autowired Annotation을 이용하여 Filed로 정의한다.
BaseDao에 SqlSessionFactory를 PostConstruct Annotation을 이용하여 SqlSessionDaoSupport sqlSessionFactory를 주입한다.
'Spring Framrwork' 카테고리의 다른 글
[Spring Boot] Properties Configuration (0) | 2018.08.13 |
---|---|
[Spring Boot] Transaction AOP 설정 (0) | 2018.08.13 |
[Spring Boot] Intercepor 적용 (0) | 2018.08.13 |
[Spring Boot] Filter 적용 (0) | 2018.08.13 |
[Spring Boot] welcome-file-list 적용 (0) | 2018.08.13 |