빠에야는 개발중

스프링 퀵 스타트 : chap 5-1 본문

공부/스프링

스프링 퀵 스타트 : chap 5-1

빠에야좋아 2018. 2. 4. 04:37

Mybatis 적용

마지막 챕터는 퍼시스턴스 레이어에 대해서 다룬다. 먼저 mybatis를 사용하여 굉장히 보기 싫었던 JDBC 접속 코드를 깔끔하게 만들자.

입문

스프링에 적용하기 전에 별도의 프로젝트를 만들어 적응해보고자 한다.


먼저 디펜던시를 설정해주고, IDE 마켓에서 java orm plugin을 설치해준다. 이녀석이 있으면 편하게 xml 파일을 만들 수 있다.


VO는 기존 스프링 프로젝트에서 사용하던 BoardVO를 그대로 사용한다.


다음은 mapper xml을 작성한다. 파라미터의 물음표를 이름으로 바꿔주는 것 외에는 별다른 작업이 필요없다.

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
<?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="BoardDAO">
    <insert id="insertBoard">
        insert into board(seq, title, writer, content) 
            values((select nvl(max(seq), 0)+1 from board), #{title}, #{writer}, #{content})
    </insert>
    
    <update id="updateBoard">
        update board set title=#{title}, content=#{content} where seq=#{seq}
    </update>
    
    <delete id="deleteBoard">
        delete board where seq=#{seq}
    </delete>
 
    <select id="getBoard" resultType="board">
        select * from board where seq=#{seq}
    </select>
 
    <select id="getBoardList" resultType="board">
        select * from board 
        where title like '%'||#{searchKeyword}||'%' 
        order by seq desc
    </select>
</mapper>
 
cs

이제 mybatis 환경설정 파일을 작성하자. db.properties에 접속 정보를 입력하고, sql-map-config.xml에서 프로퍼티로 가져온다.


db.properties
1
2
3
4
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:tcp://localhost/~/test
jdbc.username=sa
jdbc.password=
cs

sql-map-config.xml
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
<?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>
    <!-- Properties 파일 설정 -->
    <properties resource="db.properties" />
    
    <!-- Alias 설정 -->
    <typeAliases>
        <typeAlias type="com.springbook.biz.board.BoardVO" alias="board"></typeAlias>
    </typeAliases>
    
    <!-- DataSource 설정 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClassName}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    
    <!-- Sql Mapper 설정 -->
    <mappers>
        <mapper resource="mappings/board-mapping.xml" />
    </mappers>
</configuration>
 
cs

본격적으로 SqlSession 객체를 생성할텐데, iBatis의 SqlSessionFactory를 사용한다. 이 팩토리 클래스 객체로부터 SqlSession 객체를 얻어낼 것이다.

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
package com.springbook.biz.util;
 
import java.io.Reader;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
public class SqlSessionFactoryBean {
    private static SqlSessionFactory sessionFactory = null;
    static {
        try{
            if(sessionFactory == null) {
                Reader reader = Resources.getResourceAsReader("sql-map-config.xml");
                sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static SqlSession getSqlSessionInstance() {
        return sessionFactory.openSession();
    }
}
 
cs


다음은 DAO를 작성한다. 이전에 connection, statement 등을 다룰 때보다 훨~씬 간결해진 코드를 볼 수 있다.

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
38
39
40
package com.springbook.biz.board.impl;
 
import java.util.List;
 
import org.apache.ibatis.session.SqlSession;
 
import com.springbook.biz.board.BoardVO;
import com.springbook.biz.util.SqlSessionFactoryBean;
 
public class BoardDAO {
    private SqlSession mybatis;
    
    public BoardDAO() {
        mybatis = SqlSessionFactoryBean.getSqlSessionInstance();
    }
    
    public void insertBoard(BoardVO vo) {
        mybatis.insert("BoardDAO.insertBoard", vo);
        mybatis.commit();
    }
    
    public void updateBoard(BoardVO vo) {
        mybatis.update("BoardDAO.updateBoard", vo);
        mybatis.commit();
    }
    
    public void deleteBoard(BoardVO vo) {
        mybatis.delete("BoardDAO.deleteBoard", vo);
        mybatis.commit();
    }
    
    public BoardVO getBoard(BoardVO vo) {
        return mybatis.selectOne("BoardDAO.getBoard", vo);
    }
    
    public List<BoardVO> getBoardList(BoardVO vo) {
        return mybatis.selectList("BoardDAO.getBoardList", vo);
    }
}
 
cs


테스트해보면 잘 실행됨을 알 수 있다.

늘 그렇듯 내용은 무시하자.


스프링과 연동

Mybatis에서는 스프링과 연동할 수 있도록 라이브러리를 제공한다. 디펜던시 설정으로 다운받아준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- Mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.3.1</version>
</dependency>
 
<!-- Mybatis Spring -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.4</version>
</dependency>
cs

앞서 사용했던 mapper와 환경설정 xml 파일들을 가져온 후, datasource 부분만 제거한다. 이미 applicationContetxt.xml에 설정되어있기 때문이다.


스프링과 연동하는 방법은 SqlSessionDaoSupport를 상속하는 방법과 SqlSessionTemplate을 빈으로 등록하는 방법 두 가지가 있는데, 후자를 사용할 것이다.

SqlSessionTemplate에는 setter 메소드가 없기 때문에 생성자 인젝션을 해준다.

1
2
3
4
5
6
7
8
9
<!-- Mybatis 설정 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
 
<bean class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg ref="sqlSession"></constructor-arg>
</bean>
cs


DAO를 수정한다. 앞서 연습해본 것과 같다.


다이나믹 쿼리를 사용하여 조건에 맞게 쿼리를 사용할 수도 있다.

1
2
3
4
5
6
7
8
9
10
11
<select id="getBoardList" resultType="board">
    select * from board 
    where 1 = 1 
    <if test="searchCondition == 'TITLE'">
        and title like '%'||#{searchKeyword}||'%'
    </if>
    <if test="searchCondition == 'CONTENT'">
        and content like '%'||#{searchKeyword}||'%'
    </if>
    order by seq desc
</select>
cs


'공부 > 스프링' 카테고리의 다른 글

Controller의 String 리턴  (0) 2018.02.05
스프링 퀵 스타트 : chap 5-2  (0) 2018.02.05
스프링 퀵 스타트 : chap 4-2  (1) 2018.02.01
스프링 퀵 스타트 : chap 4-1  (1) 2018.01.31
스프링 퀵 스타트 : chap 3-2  (1) 2018.01.30
Comments