'마이바티스'에 해당되는 글 1건

  1. 2018.06.11 스프링 db, 마이바티스 세팅 (java config)
반응형


# 사용 환경

스프링 버전 : 4.3.2

db : mysql


본 포스팅에서는 mysql, mybatis 세팅 방법을 기록한다.


1. pom.xml 수정

 - pom.xml 파일에 아래의 내용을 추가한다. db, mybatis 관련 내용이 모두 담겨있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!-- MySQL -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>
 
<!-- MyBatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
</dependency>
 
<!-- MyBatis-Spring -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
</dependency>
 
<!-- Spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
cs



2. 자바 설정파일 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Configuration
public class DatabaseConfiguration {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    @Bean
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource source = new DriverManagerDataSource();
        source.setDriverClassName("com.mysql.cj.jdbc.Driver");
        // 자바 설정으로 쓸 때에는 url에 &을 &amp; 로 치환하면 에러나더라.        
        source.setUrl("jdbc:mysql://localhost:3306/test_db?serverTimezone=UTC&useSSL=false");
        source.setUsername("user01");
        source.setPassword("1234");
        
        return source;
    }
    
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis/config/mybatis-config.xml"));
        sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources("classpath:mybatis/mapper/*.xml"));
        
        return sqlSessionFactoryBean.getObject();
    }
    
    
    @Bean
    public SqlSession sqlSession() throws Exception {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory());
        return sqlSessionTemplate;
    }
    
}
 
cs
1 : 이 파일이 설정 파일임을 알리는 어노테이션
23-24 : 마이바티스 설정파일, 맵퍼 xml의 위치.. 없이 세팅도 가능하지만 일단 추가.

3. 마이바티스 xml 파일들 추가
 - 아래와 같이 경로를 생성하고 파일을 넣어둔다. (경로는 2번에서 설정한 경로에 맞춘 것)
각 파일들의 내용은 아래와 같다
 3-1. mybatis-config.xml
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
 
<configuration>
    
</configuration>
cs

 

 3-2. test-mapper.xml

1
2
3
4
5
6
7
8
9
10
<?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="com.post.javaconfig.dao.TestDao">
 
</mapper>
  
cs

 - 인터페이스 파일과 매칭이 되어야 에러가 나지 않는다.

 3-3. TestDao 인터페이스 생성
1
2
3
4
public interface TestDao {
    @Select("select 1")
    int test();    
}
cs
- 쿼리는 xml 파일에서 작성 할 수도, 인터페이스에서 직접 작성할 수도 있다.
- 아래 메소드를 호출하면 어노테이션에 적힌 쿼리 실행 결과가 리턴된다.

아래 이미지는 세팅된 파일들의 트리이다.



여기까지 세팅이 끝났다면 db, mybatis 연동이 끝이다.
아래는 기본 생성되는 HomeController 파일에 확인용 코드를 추가한 것이다.
서버를 실행하고 루트 페이지로 접속하면 sts상에 쿼리 결과가 찍힐 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Controller
public class HomeController {
    
    // 요기 추가
    @Autowired
    private SqlSession sqlSession;
    
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        
        // 테스트를 위해 추가
        // ********************************
        TestDao testDao = sqlSession.getMapper(TestDao.class);
        System.out.println(testDao.test());        
        // ********************************
        
        logger.info("Welcome home! The client locale is {}.", locale);
        
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        
        String formattedDate = dateFormat.format(date);
        
        
        model.addAttribute("serverTime", formattedDate );
        
        return "home";
    }
    
}
cs




Posted by NULL..
,