본문 바로가기
Programming/Spring

[spring] MyBatis 구현

by NAMP 2016. 4. 25.

[spring] MyBatis 구현

http://www.mybatis.org/mybatis-3/ko/

마이바티스는 무엇인가?

마이바티스는 개발자가 지정한 SQL, 저장프로시저 그리고 몇가지 고급 매핑을 지원하는 퍼시스턴스 프레임워크이다. 마이바티스는 JDBC로 처리하는 상당부분의 코드와 파라미터 설정및 결과 매핑을 대신해준다. 마이바티스는 데이터베이스 레코드에 원시타입과 Map 인터페이스 그리고 자바 POJO 를 설정해서 매핑하기 위해 XML과 애노테이션을 사용할 수 있다.

SqlSession 이 필요하다.

    @Autowired
    SqlSession session;

MyBatis root element 는 configuration

<configuration>
</configuration>

mapper 파일 목록 등록
<mappers>

<configuration>
    <mappers>
        <mapper resource="mappers/usermapper_m.xml"/>
    </mappers>
</configuration>

mapper 파일 doctype

<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

namespace 를 반드시 입력해야 한다.

<mapper namespace="user">
</mapper>

iBatis 에서 사용한 mapper 파일에서
MyBatis 구문으로 변경한다.

<?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="user">
    <insert id="add" parameterType="user.vo.UserVO">
        insert into userinfo (userid, username, userpwd,
        email, phone,address)
        values (#{userid}, #{username}, #{userpwd}, #{email}, #{phone}, #{address})
    </insert>
    
    <select id="login" parameterType="user.vo.UserVO" resultType="user.vo.UserVO">
        select * from userinfo where userid=#{userid} and userpwd = #{userpwd}
    </select>
    
    <select id="getuser" resultType="user.vo.UserVO">
        select * from userinfo where userid = #{userid}
    </select>

    <select id="list" resultType="user.vo.UserVO">
        select * from userinfo
    </select>
    
    <update id="update" parameterType="user.vo.UserVO">
        update userinfo set email=#{email},phone=#{phone},address=#{address} where
        userid = #{userid}
    </update>
    
    <delete id="delete">
        delete from userinfo where userid = #{userid}
    </delete>
    
</mapper>

where 절을 변경한다.

    <select id="search" parameterType="hashMap" resultType="user.vo.UserVO">
        select * from userinfo
        <where>
            <if test="userid != null"> userid like '%'||#{userid}||'%'    </if>
            <if test="username != null"> username like '%'||#{username}||'%'    </if>
            <if test="email != null"> email like '%'||#{email}||'%'    </if>
        </where>
    </select>

applicationContext 등록

    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis_config.xml"></property>
    </bean>    

sqlSessionTemplate 을 추가한다.

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactoryBean"/>
    </bean>

getUserList 구현

    @Override
    public List<UserVO> getUserList() {
        System.out.println("UserDAO_MyBatis - getUserList");
        return sqlSession.selectList("user.list");
    }

DAO 를 모두 구현한다.

@Repository("mybatis")
public class UserDAO_MyBatis implements UserDAO {

    @Autowired
    SqlSession sqlSession;
    
    @Override
    public UserVO login(String id, String pw) {
        System.out.println("UserDAO_MyBatis");
        UserVO vo = new UserVO();
        vo.setUserid(id);
        vo.setUserpwd(pw);
        return sqlSession.selectOne("user.login", vo);
    }

    @Override
    public int addUser(UserVO user) {
        System.out.println("UserDAO_MyBatis - getUserList");
        return sqlSession.insert("user.add", user);
    }

    @Override
    public UserVO getUser(String id) {
        return sqlSession.selectOne("user.getuser", id);
    }

    @Override
    public List<UserVO> getUserList() {
        System.out.println("UserDAO_MyBatis - getUserList");
        return sqlSession.selectList("user.list");
    }

    @Override
    public int updateUser(UserVO user) {
        return sqlSession.insert("user.update", user);
    }

    @Override
    public int removeUser(String id) {
        return sqlSession.insert("user.delete", id);
    }

    @Override
    public List<UserVO> searchUser(String condition, String keyword) {
        Map<String, String> map = new HashMap<String, String>();
        map.put(condition, keyword);
        return sqlSession.selectList("user.search", map);
    }

}

export file : https://goo.gl/lHh3eZ

댓글