'프로그래밍/ibatis'에 해당되는 글 4건

  1. 2014.11.18 [MyBatis] $ 과 # 차이점
  2. 2014.11.18 iBatis 복수 parameter넘기는법
  3. 2014.10.28 Mybatis 기본 사용법
  4. 2014.10.14 [스크랩]resultMap, resultClass, parameterClass
728x90

sqlMapper를 작성할 때 #과 $ 기호의 차이점은 아래와 같다.


# : 매개변수로 전달받은 파라메터를 그대로 삽입한다.

ex) 만약 아래와 같이 SQL이 작성되어 있다고 네임 스페이스는 test.select 라고 하자.

    select * from MEMBER where name = #{name}

    호출시 인자 전달 방법은 아래와 같다.

    getSqlSession.selectOne("test.select", "이지형");


$ : key와 value로 이루어진 Map 형태로 전달된다.

    select * from MEMBER where name = ${name}

    이라고 하면 파라메터 타입을 HashMap으로 넘겨줘야하며 

    name(key)에 해당하는 값(value) SQL 구문에 넣어주게 된다.

    HashMap<String, String) map = new HashMap<String, String>();

    map.put("name", "이지형");

    getSqlSession.selectOne("test.select", map);






1. #는 쿼리가 수행될 때, 다음과 같이 된다 

SELECT * FROM USER 

WHERE 
col = ?  


parameter : [값]


?에 bind된 값이 들어가게 된다. 

이 쿼리의 컴파일 된 내용을 재사용 할 수 있고, 파라미터에 따라 대입해주므로 효율적이다.
내부적으로 preparedStatement 객체에서 ? 에 들어갈 파라미터의 값을 set 해줌으로써 사용이 된다.
 
preparedStatement는 한번 수행한 쿼리를 캐싱하는 객체


사용 용도 >>

#일 경우, 에 사용한다.

myBatis : 컬럼명 = #{값}   
iBatis : 컬럼명 = #값#

* 쿼리에 작은 따옴표가 붙게 된다.


2. $는 쿼리가 수행될 때, 다음과 같이 된다

SELECT * FROM USER
WHERE 
col = 



값이 넣어진 쿼리 자체로 수행이 된다.(상수)
즉, 문장 전체가 preparedStatement가 된다.

사용 용도 >>

$일 경우는 컬럼명이 동적으로 바뀌어야 할 때 사용한다. 또는 테이블명.

myBatis : ${컬럼명} = #{값}   
iBatis : $컬럼명$ = #{값}

* 쿼리에 작은따옴표가 붙지 않는다. 
값에 $를 사용하면 스트링의 경우 작은따옴표로 감싸지지 않기 때문에 에러 발생한다.


이렇게 사용하지 않으면 unknown column 이나 There is no readable property named  등등의 에러가 뜨게 된다


출처 : http://warmz.tistory.com/744
   http://marobiana.tistory.com/60


'프로그래밍 > ibatis' 카테고리의 다른 글

iBatis 복수 parameter넘기는법  (0) 2014.11.18
Mybatis 기본 사용법  (0) 2014.10.28
[스크랩]resultMap, resultClass, parameterClass  (0) 2014.10.14
Posted by 앗뜨거
,
728x90

DAO용도인 .JAVA 파일에 다음과 같은 메서드를 만들어 넣는다 단지 map한개만 만들어서 보내고 싶은 파라미터 다 집어 넣으면 된다. 변수 이름과 key값은 같은게 좋을 듯 하다. 

그리고 그냥 MAP만 한개 던저주면 게임 끝이다.

아 이 얼마나 쉬운가 이거 어찌 하나 몇시간 생각했었는데. 혹시 되나하고 해봤는데 되니까 참 .. iBatis 레퍼런스 찾아봐도 되는데 이리 하면 기억에 오래 남아서 머리 싸매고 고민하는게 난 좋다 ㅎㅎㅎ(멍청한 짓인가) 이 프레임워크 만든사람이 나보다 똑똑한 사람일텐데 파라미터 하나 복수로 넘길수 없는 걸 만들었을리 없다는 확신이 있었다. ㅋㅋㅋㅋㅋ

public ArrayList getTimePriceList(String contractCode,String sdate,String edate,String stime,String etime) throws SQLException {
         HashMap map = new HashMap();
         map.put("contractCode", contractCode);
         map.put("sdate", sdate);
         map.put("edate", edate);
         map.put("stime", stime);
         map.put("etime", etime);
         
   list=(ArrayList)sqlMap.queryForList("getTimePriceList",map);  
   return list;
  }

SQL을 지정한 XML에서 다음과 같이 parameterClass를 맵으로 하면 된다. 꼭 MAP이 아니라 list 나 table도 되는지는 귀찮아서 안해봤다. 뭐 되지 않을까 싶다 안되면 되는거 쓰면 되니까 뭐 문제는 없을 듯하다. 
어짜피 parameter넘길뿐인데 뭐든 어떠냐 잘 넘어가기만 하면 되지 ㅎㅎㅎ

<select id="getTimePriceList" parameterClass="java.util.HashMap" resultClass="timeprice">
    <![CDATA[SELECT contractCode,date,time,close,sum(vol) as sumvol from timeprice 
    where 
    contractCode=#contractCode# 
    and date>=#sdate# 
    and date<#edate# 
    and time>=#stime# 
    and time<#etime# 
    group by close order by close
    ]]></select>


출처 : http://hedging.tistory.com/entry/iBatis-%EB%B3%B5%EC%88%98-parameter%EB%84%98%EA%B8%B0%EB%8A%94%EB%B2%95

'프로그래밍 > ibatis' 카테고리의 다른 글

[MyBatis] $ 과 # 차이점  (0) 2014.11.18
Mybatis 기본 사용법  (0) 2014.10.28
[스크랩]resultMap, resultClass, parameterClass  (0) 2014.10.14
Posted by 앗뜨거
,
728x90

MyBatis는 iBATIS의 새로운 버전으로 국내에서 가장 많이 사용되는 ORM Framework[각주:1] 중 하나이다. MyBatis는 문서화가 잘 되어 있다고 하지만 막상 실전에 적용시키기에는 이전 버전인 iBATIS에 비해 예제가 부족한 듯하여 자료 정리겸 레퍼런스를 만들어 볼까 한다.

우선 MyBatis를 설정하고 간단한 예제를 만들어 본 다음, Spring 3로 Bean을 등록하는 예제로 확장시켜 볼 예정이다.

본 예제는 다음과 같은 개발환경하에서 작성되었다.

  • Eclipse Java EE IDE (Juno)
    • PropertiesEditor (by Sou Miyazaki)
  • Java SE 6
  • MyBatis-3.1.1
  • JUnit 4

1. MySQL Table


1
2
3
4
5
6
7
CREATE TABLE user (
    id INT(5) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(16) NOT NULL,
    password VARCHAR(16) NOT NULL,
    level INT(2) NOT NULL DEFAULT '0',
    reg_date DATE NOT NULL
);

2. Configuration


development.properties


1
2
3
4
url=jdbc:mysql://localhost/development?characterEncoding=utf-8
driver=com.mysql.jdbc.Driver
user=development
pass=test123



mysql-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
33
34
35
36
37
38
39
40
41
<p><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
<configuration>
    <properties resource="exercise/mybatis3/persistence/development.properties"/>
     
    <settings>
        <setting name="defaultExecutorType" value="REUSE"/>
        <setting name="useGeneratedKeys" value="true"/>
    </settings>
     
    <typeAliases>
    <!-- Type Aliases List -->   
    </typeAliases>
     
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="JNDI">
                <property name="initial_context" value="java:comp/env" />
                <property name="data_source" value="jdbc/insure"/>
            </dataSource>
        </environment>
         
        <environment id="testing">
            <transactionManager type="MANAGED">
                <property name="closeConnection" value="false"/>
            </transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${user}" />
                <property name="password" value="${pass}" />
            </dataSource>
        </environment>
    </environments>
     
    <mappers>
    <!-- Mapper List -->
    </mappers>
</configuration></p>

3. SQL Mapper (CRUD)

UserMapper.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<mapper namespace="exercise.mybatis3.persistence.UserMapper">
    <insert id="add" parameterType="User"
            useGeneratedKeys="true" keyProperty="id">
        INSERT INTO user (username, password, level, reg_date)
        VALUES (#{username}, #{password}, 1, NOW())
    </insert>
     
    <select id="count" resultType="int">
        SELECT COUNT(*) FROM user
    </select>
</mapper>

UserMapper.java


1
2
3
4
5
6
7
8
9
10
package exercise.mybatis3.persistence;
 
import exercise.mybatis3.domain.User;
 
public interface UserMapper {
     
    public void add(User user);
     
    public int count();
}

4. Domain Object

User.java


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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package exercise.mybatis3.domain;
 
import java.io.Serializable;
 
public class User implements Serializable {
 
    private static final long serialVersionUID = 1L;
     
    private Integer id;
    private String username;
    private String password;
    private Integer level;
    private String regDate;
 
    public User() {
        // TODO Auto-generated constructor stub
    }
     
    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public Integer getLevel() {
        return level;
    }
 
    public void setLevel(Integer level) {
        this.level = level;
    }
 
    public String getRegDate() {
        return regDate;
    }
 
    public void setRegDate(String regDate) {
        this.regDate = regDate;
    }
 
}

5. Unit Test (CRUD)

TestUserMapper.java


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
41
42
43
44
45
46
47
48
49
50
package exercise.mybatis3.test;
 
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
 
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;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
 
import exercise.mybatis3.domain.User;
import exercise.mybatis3.persistence.UserMapper;
 
public class TestUserMapper {
    static SqlSessionFactory sf;
    User user;
 
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        String resource = "exercise/mybatis3/persistence/mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        sf = new SqlSessionFactoryBuilder().build(reader, "testing");
         
    }
     
    @Before
    public void setUp() {
        user = new User("user1", "1234");
    }
 
    @Test
    public void testAdd() {
        SqlSession session = sf.openSession();
         
        try {
            UserMapper mapper = session.getMapper(UserMapper.class);
             
            mapper.add(user);
            assertThat(1, is(mapper.count()));
        } finally {
            session.close();
        }
    }
 
}

출처: http://jeongsam.net/259


'프로그래밍 > ibatis' 카테고리의 다른 글

[MyBatis] $ 과 # 차이점  (0) 2014.11.18
iBatis 복수 parameter넘기는법  (0) 2014.11.18
[스크랩]resultMap, resultClass, parameterClass  (0) 2014.10.14
Posted by 앗뜨거
,
728x90

iBatis 는 실제적으로 많이 사용 하고 있거나, 그렇지 않으면 앞으로 사용 할 때

굉장히 헷갈리는 부분이 있다.


바로 어떻게 value object와 column name을 맵핑 시킬 것인가,

혹은 값들을 어떻게 jsp에 뿌릴 것 인가, 즉슨 자바 코드에 어떻게 담아서 운반 할 것인가

에 대해 많은 고민이 있다.


이제 때에 맞는 iBatis value 맵핑에 대해 알아보자.


우선, 게시판을 예로 들겠다.

1. 글 작성 후 글을 DB에 insert 시킬 시

여기선 아마 write.jsp 라는 페이지에서 form값을 vo에 담아 controller 에다 넘겨 줄 것이다.


// vo 객체를 인스턴스화 하여 가져온다

<typeAlias alias="boardVo" type="jh.board.vo.BoardVO"/>


<insert id="write" parameterClass="boardVo">


이렇게 parameterClass는 vo값을 insert만 하고 아무런 result값도 가져오지 않을 때 주로 쓰인다.


2. 글 목록들을 Select 할 때

여기선 객체 하나만 가져오는게 아니라, 객체의 리스트 제네릭을 리턴 받는다.


<resultMap id="BoardResult" class="boardVo">

<result property="num" column="num" columnIndex="1" />

<result property="author" column="author" columnIndex="2" />

<result property="title" column="title" columnIndex="3" />

<result property="content" column="content" columnIndex="4" />

<result property="writeday" column="writeday" columnIndex="5" />

<result property="readcnt" column="readcnt" columnIndex="6" />

</resultMap>


<select id="list" resultMap="BoardResult" parameterClass="boardVo">


resultMap을 이용하여 boardVo 객체의 겟/셋 변수명과 DB의 column 명을 맵핑 한 후

그 결과를 조회하여 resultMap 을 Controller단 까지 넘겨 받는다.


여기서 유심히 볼 것은 그저 select만 한다면 paramterClass가 필요 없다.

하지만 검색 시 검색명과 검색값을 select 문에 넣기 위해 paramterClass가 또 쓰여 졌다.


3. 상세글이나 업데이트 시


<select id="retrieve" resultMap="BoardResult">


<select id="updateForm" resultMap="BoardResult">


위와 마찬가지로 resultMap을 사용 하여 값을 return 받아 프레젠테이션 층에 넘겨 준다.


4. 그런데 resultClass 는 어디서 사용 될까 ?


<select id="count" resultClass="Integer">

SELECT 

COUNT( num )

FROM board

</select>


위와 같이 그냥 Integer(정수형) 으로 num의 count만 받고 싶다면 저렇게 쓰면 된다.


물론 Delete문과 같이 리턴 받을게 없고 그저 삭제만 시킨다 함은 resultMap, resultClass를 쓸 필요가 없는 것이다.


요약 하자면,

resultMap Object를 return 받을 때 사용

resultClass Integer 등 1개의 value형을 return 받을 때 사용

parameterClass Object를 ibatis DML(#num#, #title#)문에 적용 시키고 싶을 때 사용




출처: http://denodo1.tistory.com/entry/resultMap-resultClass-parameterClass-%EC%97%90-%EA%B4%80%ED%95%9C-%EA%B3%A0%EC%B0%B0

'프로그래밍 > ibatis' 카테고리의 다른 글

[MyBatis] $ 과 # 차이점  (0) 2014.11.18
iBatis 복수 parameter넘기는법  (0) 2014.11.18
Mybatis 기본 사용법  (0) 2014.10.28
Posted by 앗뜨거
,