프로필사진
MyBatis를 이용한 DAO구현

2019. 11. 20. 15:08🔴 Spring

300x250

2. MyBatis를 이용한 DAO구현

1) SqlSessionTemplate이용

<guestMapper.xml>

<?xml version="1.0" encoding="UTF-8"?>
<!-- ver01 : SqlSessionTemplate이용하여 DAO구현 -->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace는 필수 속성 : dao에서 식별하기 위한 이름이기 때문!!! -->
<mapper namespace="com.bitcamp.guest.mapper.mybatis.guestMapper">

	<insert id="insertMessage"
		parameterType="com.bitcamp.guest.domain.Message">
		insert into guestbook_message (message_id, guest_name,
		password, message) values (GM_MID_SEQ.NEXTVAL, #{guestName},
		#{password}, #{message})
	</insert>

	<select id="selectCount" resultType="int">
		select count(*) from
		guestbook_message
	</select>

	<select id="selectList" parameterType="map" resultMap="messageResultmap">
		<!-- 크기 비교할때 CDATA사용 -->
		<![CDATA[
		select message_id, guest_name, password, message from
		( select rownum rnum, message_id, guest_name, password, message from (
		select * from guestbook_message m order by m.message_id desc ) where
		rownum <= #{endRow}) where rnum >= #{firstRow}]]>
	</select>
	
	<select id="select" resultType="com.bitcamp.guest.domain.Message">
		select * from guestbook_message where message_id = #{id}
	</select>

	<delete id="deleteMessage">
		delete from guestbook_message where message_id = #{id}
	</delete>
	
	<!-- DB상의 컬럼 이름과 자바 클래스의 변수 이름이 달라서 mapping시켜야함  -->
	<resultMap type="com.bitcamp.guest.domain.Message" id="messageResultmap">
		<id property="id" column="message_id"/> <!-- pk = id -->
		<result property="guestName" column="guest_name"/>
		<result property="password" column="password"/>
		<result property="message" column="message"/>
	</resultMap>

</mapper>

<MessageSessionTemplateDao.java>

package com.bitcamp.guest.dao;
// ★★ SQL문 작성 기능 ★★
//ver01 : SqlSessionTemplate이용하여 DAO구현
import java.util.List;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.bitcamp.guest.domain.Message;

@Repository("sessionTemplateDao")
public class MessageSessionTemplateDao {

	@Autowired
	private SqlSessionTemplate template;

	private String nameSpace = "com.bitcamp.guest.mapper.mybatis.guestMapper";

	public int insert(Message message) {
		String str = nameSpace + ".insertMessage";
		int rCnt = template.update(str, message);
		// == template.update(nameSpace+".insertMessage", message);
		return rCnt;
	}

	public int selectCount() {
		String str = nameSpace + ".selectCount";
		return template.selectOne(str);
	}

	public List<Message> selectList(Map<String, Object> params) {
		return template.selectList(nameSpace + ".selectList", params);
	}

	public Message select(int messageId) {
		return template.selectOne(nameSpace+".select", messageId);
	}

	public int deleteMssage(int messageId) {
		return template.update(nameSpace+".deleteMessage",messageId);
	}

}

<WriteMessageService.java>

package com.bitcamp.guest.service;

import org.mybatis.spring.SqlSessionTemplate;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bitcamp.guest.dao.MessageJdbcTemplateDao;
import com.bitcamp.guest.dao.MessageSessionDao;
import com.bitcamp.guest.dao.MessageSessionTemplateDao;
import com.bitcamp.guest.domain.Message;

@Service("writeService")
public class WriteMessageService implements GuestBookService {

	@Autowired
	private MessageSessionTemplateDao templateDao;

	public int write(Message message) {
			
		int rCnt = 0;
		rCnt = templateDao.insert(message);

		// 1. Connection 생성 2. dao 생성 3. insert 메소드 실행

		// Connection conn = null; try { conn = ConnectionProvider.getConnection();

		// MessageDao dao = MessageDao.getInstance();

		// rCnt = dao.insert(conn, message);

		// } catch (SQLException e) { // TODO Auto-generated catch block
		// e.printStackTrace(); }

		return rCnt;
	}

}

 

2) 자동 Mapper 생성 기능 이용 (인터페이스)

<messageMapper.xml>

<?xml version="1.0" encoding="UTF-8"?>
<!-- ver02: 자동매핑 사용 -->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace는 필수 속성 : dao에서 식별하기 위한 이름이기 때문!!! -->
<mapper namespace="com.bitcamp.guest.dao.MessageSessionDao">

	<insert id="insert" *** xml id명과 인터페이스 DAO 메소드명이 같아야 한다!!!
		parameterType="com.bitcamp.guest.domain.Message">
		insert into guestbook_message (message_id, guest_name,
		password, message) values (GM_MID_SEQ.NEXTVAL, #{guestName},
		#{password}, #{message})
	</insert>

	<select id="selectCount" resultType="int">
		select count(*) from
		guestbook_message
	</select>

	<select id="selectList" parameterType="map" resultMap="messageResultmap">
		<!-- 크기 비교할때 CDATA사용 -->
		<![CDATA[
		select message_id, guest_name, password, message from
		( select rownum rnum, message_id, guest_name, password, message from (
		select * from guestbook_message m order by m.message_id desc ) where
		rownum <= #{endRow}) where rnum >= #{firstRow}]]>
	</select>
	
	<select id="select" resultType="com.bitcamp.guest.domain.Message">
		select * from guestbook_message where message_id = #{id}
	</select>

	<delete id="deleteMssage">
		delete from guestbook_message where message_id = #{id}
	</delete>
	
	<!-- DB상의 컬럼 이름과 자바 클래스의 변수 이름이 달라서 mapping시켜야함  -->
	<resultMap type="com.bitcamp.guest.domain.Message" id="messageResultmap">
		<id property="id" column="message_id"/> <!-- pk = id -->
		<result property="guestName" column="guest_name"/>
		<result property="password" column="password"/>
		<result property="message" column="message"/>
	</resultMap>

</mapper>

<MessageSessionDao.java> (인터페이스)

package com.bitcamp.guest.dao;
//ver02: 자동매핑 사용
import java.util.List;
import java.util.Map;

import com.bitcamp.guest.domain.Message;

public interface MessageSessionDao {
	public int insert(Message message);
	public int selectCount();
	public List<Message> selectList(Map<String, Object> params);
	public Message select(int messageId);
	public int deleteMssage(int messageId);
}

<WriteMessageService.java>

package com.bitcamp.guest.service;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bitcamp.guest.dao.MessageJdbcTemplateDao;
import com.bitcamp.guest.dao.MessageSessionDao;
import com.bitcamp.guest.dao.MessageSessionTemplateDao;
import com.bitcamp.guest.domain.Message;

@Service("writeService")
public class WriteMessageService implements GuestBookService {

	@Autowired
	private SqlSessionTemplate template;

	private MessageSessionDao templateDao;

	public int write(Message message) {
		
	// dao생성
	templateDao = template.getMapper(MessageSessionDao.class);
	
		int rCnt = 0;
		rCnt = templateDao.insert(message);

		// 1. Connection 생성 2. dao 생성 3. insert 메소드 실행

		// Connection conn = null; try { conn = ConnectionProvider.getConnection();

		// MessageDao dao = MessageDao.getInstance();

		// rCnt = dao.insert(conn, message);

		// } catch (SQLException e) { // TODO Auto-generated catch block
		// e.printStackTrace(); }

		return rCnt;
	}

}

300x250