http://longbe00.blogspot.com/2015/03/mybatis-java-config.html
package com.moonv.test.config.orm;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.PlatformTransactionManager;
/**
* MyBatis 설정 클래스
*
*/
@Configuration
@MapperScan(basePackages="com.moonv.test.**.persistence",
sqlSessionFactoryRef="sqlSessionFactory", annotationClass=Repository.class)
//Mapper.class가 아니라면 annotaionClass 를 지정해주자.
//'sqlSessionFactoryRef' 세팅을 해서 'Requested bean is currently in creation: Is there an unresolvable circular reference?' 메시지가 보이면서 순환참조 예외가 발생할 수 있다. 그럼 그냥 지워주면 된다.
public class MyBatisConfig {
/**
* 스프링이 트랜잭션을 관리할때 사용하는 트랜잭션매너져를 등록한다.
* @param dataSource DataSourceConfig.class 로부터 주입받은 bean
* @return
*/
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
/**
* mybatis SqlSessionFactory 생성한다.
* @param dataSource DataSourceConfig.class 로부터 주입받은 bean
* @return
* @throws Exception
*/
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
//sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("dbms/mybatis-config.xml"));
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:com/moonv/test/**/persistence/*.xml"));
/*
//applicationContext 로 세팅하는 방법
sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources("classpath*:com/moonv/test/**/persistence/*.xml"));
*/
return sqlSessionFactoryBean.getObject();
}
/**
* SqlSession 생성
* @param sqlSessionFactory 바로 위에 선언한 sqlSessionFactory 빈. 한 메소드에서 여러 개의 파라미터를 주입받을 수 있다.
* @return SqlSession
* @throws Exception
*/
@Bean(name="sqlSession")
public SqlSession sqlSession(SqlSessionFactory sqlSessionFactory) throws Exception{
SqlSession sqlSession = new SqlSessionTemplate(sqlSessionFactory);
return sqlSession;
}
}
'Web > SpringBoot' 카테고리의 다른 글
[spring] produces (0) | 2019.08.13 |
---|---|
Jersey: A message body writer for Java Class and MIME mediatype application/json was not found (0) | 2019.08.01 |
Access a File from the Classpath in a Spring Application (0) | 2019.04.10 |
Spring Boot - Apache Kafka 카프카 연동 (0) | 2019.03.29 |
[mybatis] 다중 Database Setting (0) | 2019.03.21 |
댓글