728x90
1. 메이븐 설치(root-context.xml)
버전에 맞는 mybats, spring-mybatis 설치
3. SqlSession,SqlSessionFactoryBean 빈등록
(mappers 경로 설정)
typeAliasesPackage 설정은 해당 패키지 경로 풀로 작성하지 않고 dto 사용 가능
xml 빈등록 방식을 java config로 변경
package com.jurib.movie.config;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
@Configuration
@ComponentScan("com.jurib.movie")
@EnableAspectJAutoProxy
@MapperScan("com.jurib.movie.model.dao") //mapperScannerConfigurer() 빈 대체
public class ApplicationConfig {
// @Bean
// MapperScannerConfigurer mapperScannerConfigurer() {
// MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
// // mapper 인터페이스 패키지 경로
// mapperScannerConfigurer.setBasePackage("com.jurib.movie.model.dao");
//
// return mapperScannerConfigurer;
// }
@Bean
DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/moviedb?serverTimezone=UTC");
dataSource.setUsername("아이디");
dataSource.setPassword("패스워드");
return dataSource;
}
@Bean
SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
//mapper파일 dto 풀 패키지 이름 안적어 줘도 된다.
sqlSessionFactory.setTypeAliasesPackage("com.jurib.movie.model.dto");
// mapper xml 파일위치
sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mappers/*.xml"));
return sqlSessionFactory.getObject();
}
@Bean
SqlSessionTemplate sqlSession(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
4, mapper 파일 생성 및 mybatis-config.xml 파일 생성
5. 인터페이스 레포지토리 작성(mapper와 매칭)
@Mapper, @Repository 어노테이션 필수
6. mapper파일 적용
mapper 태그 namespace는 mapper와 매칭되는 dao, repository 풀 패키지 및 인터페이스 이름으로 생성
sql id는 이터페이스 함수명으로 작성
7 Service 클래스 작성
참고
728x90