JNB
rss

skin by 이글루스

JAVA & JSP

ibatis3(mybatis) 10.11.08 11:31
iBatis 3 을 요리해보자.

iBatis2와 비교해서 테이블 매핑(관계설정) 기능이 추가되었고 귀찮은 코드 생성을 많이 줄여준다.

바로 예제를 보자.
- 예제는 Oracle 과 scott 계정을 사용했다.

1. vo(Dept, Emp)를 생성하자.
- 예제에서는 toString, hashCode equals 등은 재구현하지 않았다.

001.package com.yhjung.scott.vo;
002.  
003./**
004. * @author Administrator
005. *
006. */
007.public class Dept
008.{
009.private int deptNo;
010.private String dName;
011.private String loc;
012.public int getDeptNo()
013.{
014.return deptNo;
015.}
016.public void setDeptNo(int deptNo)
017.{
018.this.deptNo = deptNo;
019.}
020.public String getdName()
021.{
022.return dName;
023.}
024.public void setdName(String dName)
025.{
026.this.dName = dName;
027.}
028.public String getLoc()
029.{
030.return loc;
031.}
032.public void setLoc(String loc)
033.{
034.this.loc = loc;
035.}
036.}
037.===================================================================================
038.package com.yhjung.scott.vo;
039.  
040.import java.util.Date;
041.  
042./**
043. * @author Administrator
044. *
045. */
046.public class Emp
047.{
048.private int empNo;
049.private String eName;
050.private String job;
051.private int mgr;
052.private Date hireDate;
053.private int sal;
054.private int comm;
055.private int deptNo;
056.private Dept dept;
057.public int getEmpNo()
058.{
059.return empNo;
060.}
061.public void setEmpNo(int empNo)
062.{
063.this.empNo = empNo;
064.}
065.public String geteName()
066.{
067.return eName;
068.}
069.public void seteName(String eName)
070.{
071.this.eName = eName;
072.}
073.public String getJob()
074.{
075.return job;
076.}
077.public void setJob(String job)
078.{
079.this.job = job;
080.}
081.public int getMgr()
082.{
083.return mgr;
084.}
085.public void setMgr(int mgr)
086.{
087.this.mgr = mgr;
088.}
089.public Date getHireDate()
090.{
091.return hireDate;
092.}
093.public void setHireDate(Date hireDate)
094.{
095.this.hireDate = hireDate;
096.}
097.public int getSal()
098.{
099.return sal;
100.}
101.public void setSal(int sal)
102.{
103.this.sal = sal;
104.}
105.public int getComm()
106.{
107.return comm;
108.}
109.public void setComm(int comm)
110.{
111.this.comm = comm;
112.}
113.public int getDeptNo()
114.{
115.return deptNo;
116.}
117.public void setDeptNo(int deptNo)
118.{
119.this.deptNo = deptNo;
120.}
121.public Dept getDept()
122.{
123.return dept;
124.}
125.public void setDept(Dept dept)
126.{
127.this.dept = dept;
128.}
129.}



2. Mapper 작성하기
* dept-mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
<mapper namespace="com.yhjung.scott.vo.Dept">

<resultMap type="Dept" id="deptResult">
<id column="deptNo" property="deptNo" />
<result column="dName" property="dName" />
<result column="loc" property="loc" />
</resultMap>

<select id="selectList" resultType="java.util.List">
select * from dept
    </select>
<select id="select" parameterType="int" resultType="Dept"
resultMap="deptResult">
select * from
dept where deptNo = #{id}
   </select>


<insert id="insert" parameterType="Dept">

INSERT INTO SCOTT.DEPT (
  DEPTNO, DNAME, LOC) 
VALUES #{deptNo},
#{dName},
#{loc});
    </insert>

<delete id="delete" parameterType="int">
delete from dept where
deptNo = #{deptNo}
   </delete>

<delete id="deleteAll">
delete from dept
  </delete>
</mapper>

* emp-mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
<mapper namespace="com.yhjung.scott.dao.EmpDAO">
    <resultMap type="Emp" id="empResult">
        <id column="empNo" property="empNo" />
        <result column="eName" property="eName" />
        <result column="job" property="job" />
        <result column="mgr" property="mgr" />
        <result column="hireDate" property="hireDate" />
        <result column="sal" property="sal" />
        <result column="comm" property="comm" />
        <result column="deptNo" property="deptNo" />
        <collection property="dept" ofType="Dept" resultMap="deptResult"/>
    </resultMap>
   
    
    <select id="selectList" resultType="java.util.List">
     select * from emp
    </select>
    <select id="select" parameterType="int" resultType="Emp"
        resultMap="empResult">
        select * from
        emp where empNo = #{id}
   </select>
  
   <select id="selectJoin" parameterType="int" resultType="Emp"
        resultMap="empResult">
        select a.*, b.* from
        emp a, dept b where a.deptno = b.deptno and empNo = #{id}
   </select>
  
    <insert id="insert" parameterType="Emp">
        
        INSERT INTO SCOTT.EMP (
  EMPNO, ENAME, JOB, 
  MGR, HIREDATE, SAL, 
  COMM, DEPTNO) 
VALUES ( #{empNo},
#{eName},
#{job},
#{mgr},
sysdate,
#{sal},
#{comm},
#{deptNo});
    </insert>
    
    <delete id="delete" parameterType="int">
        delete from emp where
        empNo = #{empNo}
  </delete>
  
  <delete id="deleteAll">
        delete from emp
  </delete>
</mapper>

3. ibatis 설정 작성
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
<configuration>
    <typeAliases>
        <typeAlias type="com.yhjung.scott.vo.Emp"
            alias="emp" />
        <typeAlias type="com.yhjung.scott.vo.Dept"
            alias="dept" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" 
                    value="oracle.jdbc.driver.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:ora11" />
                <property name="username" value="scott"/>
                <property name="password" value="해당하는비밀번호입력"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
     <mapper resource="com/yhjung/scott/xmls/dept-mapper.xml" />
        <mapper resource="com/yhjung/scott/xmls/emp-mapper.xml" />
    </mappers>
</configuration>

4. DAO 인터페이스 생성
package com.yhjung.scott.dao;

import com.yhjung.scott.vo.Emp;

public interface EmpDAO
{
public Emp selectJoin(int deptNo);
public Emp selevtEmp(int empNo);
}

5. Main 클래스 작성
(* TDD에 맞춰 TEST프레임웍을 사용하여 작성해도 된다.)
import java.io.IOException;
import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.yhjung.scott.dao.EmpDAO;
import com.yhjung.scott.vo.Emp;

/**
 * 
 */

/**
 * @author Administrator
 *
 */
public class Main
{

private static final String IBATIS_CONFIG = "com/yhjung/scott/xmls/ibatis-config.xml";

/**
* @param args
*/
public static void main(String[] args)
{
try
{
SqlSession session = createSqlMapper().openSession();
EmpDAO dao = session.getMapper(EmpDAO.class);
//Emp emp = (Emp) session.selectOne("com.yhjung.scott.vo.Emp.selectJoin", new Integer(7782));
Emp emp = dao.selectJoin(7782);
System.out.println(emp.getDept().getdName());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

}
private static SqlSessionFactory createSqlMapper() throws IOException 
{
        Reader reader = Resources.getResourceAsReader(IBATIS_CONFIG);
        return new SqlSessionFactoryBuilder().build(reader);
    }

}

** iBatis3 에서는 DAO패턴을 멋지게(?) 지원해주고 있다.
위의 emp-mapper.xml의 <mapper namespace="com.yhjung.scott.dao.EmpDAO"> 을 보면
dept-mapper.xml의 <mapper namespace="com.yhjung.scott.vo.Dept"> 와 다르다.
ps. 다른 문서에서는 EmpMapper 라는 형태로 설명하기도 한다.
1. DAO 클래스(인터페이스)는 vo 클래스의 이름에 DAO를 추가한 이름이다.(EmpDAO)
2. DAO 패턴을 사용하기 위해서는 namespace(mapper xml문서) 기술부분에 vo를 기술하는 대신 dao 클래스 이름을 기술해야 한다.

ibatis3_ex.zip


        

    
Copyright 1999-2018 Zeroboard / skin by JY