4,552,465 th visitor since 2017.2.1 ( Today : 238 )
Programming
No. 418
Name. swindler
Subject. iBatis 시작하기
Main Cate. Java
Sub Cate.
Date. 2007-12-24 15:49
Hit. 5053 (211.36.27.8)
File.
IBatis 가 무엇입니까?

DB를 xml 형식으로 좀더 효율적으로 사용하자는 것입니다.
java 파일에서 db를 사용할때, xml에 따로 빼서 사용하자는 건데...
hibernate란 것도 있습니다.

이 IBatis란 것을 spring+Ibatis, struts+Ibatis로 쓰기도 하고, log4j+Ibatis로도 쓰기도 합니다.



1)
http://ibatis.apache.org/javadownloads.html
일단 위 사이트에서 iBatis를 다운로드 받으세요.

lib 안의 jar 파일들은 적당히 classpath가 잡히도록 설정하면 된다.


Table 이름과 속성은 아래와 같습니다.
tb_Person{
int pid,
varchar pname
}


이제 가장 간단한 select 쿼리를 날리는 예제를 iBatis로 작성하겠습니다.

select pid,pname from tb_Person where pid=2222;

이걸 만들겁니다.



그냥 아래처럼 코딩하면 됩니다. 이것이 model1 방식입니다.
db 이름을 testDB이며 로그인 아이디는 loginId, 패스워드는 1111, 로그인포트 3306인 경우.


import java.sql.*;

class Driver {
public static void main(String argv[]) {
try {
Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("jdbc 드라이버 로딩 성공");
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
String url = "jdbc:mysql://localhost:3306/testDB";
Connection con = DriverManager.getConnection(url,"loginId","1111");
System.out.println("mysql 접속 성공");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select pid from tb_Person where pid=2222");
System.out.println("Got result:");
while(rs.next()) {
String no= rs.getString(1);
System.out.println(" no = " + no);
}
stmt.close();
con.close();
} catch(java.lang.Exception ex) {
ex.printStackTrace();
}
}
}





이걸 iBatis 기반으로 변경하자면
아래와 같은 총 6개의 파일들이 필요합니다.

3개의 java 파일과,

1. MyAppSqlMapConfig.java (ibatis와의 connectionPool 생성 및 db문xml 파싱)
2. Person.java (id 값을 가져오기 위한 person 클래스입니다.)
3. DBTest.java ( 이안에 main이 있습니다.)



3개의 설정 파일은 apache-tomcat/webapps/myapp/WEB-INF/classes 에 둡니다.

1. Person.xml (table을 가지고 놀 db 쿼리문을 여기에 xml로 작성하셔야합니다.)
2. SqlMapConfig.properties (db 연결용 connect 파일, id, pass가 들어있음)
3. SqlMapConfig.xml (ibatis의 핵심 설정 파일. Person.xml등 정의)


설정 파일의 소스를 먼저 본후, 소스를 하나하나 보겠습니다.

1. Person.xml

<?xml version="1.0"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="Person">
<select id="getPerson" resultClass="Person">
SELECT pid as id,pname as name

FROM tb_Person
WHERE
pid = #value#
</select>
</sqlMap>


pid as id에서 이 id를 알리어스라고 하는데, 이렇게 as id로 알리아스를 해주어야,
자바 프로그램에서 사용이 가능합니다.
이 id라는 것은 Person.java 라는 프로그램에서 실제로 선언한 프로그램 변수명이어야 합니다.



2. SqlMapConfig.properties

driver=org.gjt.mm.mysql.Driver
url=jdbc:mysql://localhost:3306/testDB
username=loginId
password=1111

이건 그냥 connect 설정입니다.



3. SqlMapConfig.xml


<?xml version="1.0" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!--<properties resource="examples/domain/SqlMapConfig.properties" />-->
<properties resource="WEB-INF/classes/SqlMapConfig.properties" />
<!--<properties resource="SqlMapConfig.properties" />-->
<!--These settings control SqlMap configuration details, primarily to do with transaction management. They are all optional (see the Developer Guide for more). -->
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="false"
/>
<!--Type aliases allow you to use a shorter name for long fully qualified class names. -->
<!--<typeAlias alias="order" type="testdomain.Order" />-->
<!--Configure a datasource to use with this SQL Map using SimpleDataSource.
Notice the use of the properties from the above resource -->
<transactionManager type="JDBC" >
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${driver}" />
<property name="JDBC.ConnectionURL" value="${url}" />
<property name="JDBC.Username" value="${username}" />
<property name="JDBC.Password" value="${password}" />
</dataSource>
</transactionManager>
<!--Identify all SQL Map XML files to be loaded by this SQL map. Notice the paths
are relative to the classpath. For now, we only have one… -->
<sqlMap resource="WEB-INF/classes/Person.xml" />
<!--<sqlMap resource="Person.xml" />-->
</sqlMapConfig>


별다른 설명은 필요 없을듯합니다.


자바 소스는 아래와 같습니다.

1. MyAppSqlMapConfig.java (ibatis와의 connectionPool 생성 및 db문xml 파싱)


import java.io.*;
import com.ibatis.common.resources.*;
import com.ibatis.sqlmap.client.*;

public class MyAppSqlMapConfig {
private static final SqlMapClient sqlMap;
static {
try {
String resource = "SqlMapConfig.xml";
Reader reader = Resources.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error initializing class. Cause:" + e);
}
}

public static SqlMapClient getSqlMapInstance() {
return sqlMap;
}

}




2. Person.java (id 값을 가져오기 위한 person 클래스입니다.)


import java.util.*;

public class Person {

private int id;

private String name;

// setter
public void setId (int id) { this.id = id; }

// getter
public int getId () { return id; }

public void setName (String name) { this.name = name; }

public String getName () { return name; }


}




3. DBTest.java ( 이안에 main이 있습니다.)

import java.sql.SQLException;
import java.util.*;

import com.ibatis.sqlmap.client.*;

public class DBTest {

/**
* @param args
* @throws SQLException
*/
public static void main(String argv[]) throws SQLException {
// TODO Auto-generated method stub
// select
/*
*/
selectTest();
}

public static void selectTest () throws SQLException
{
//sqlMap 초기화(MyAppSqlConfig.java)
SqlMapClient sqlMap = MyAppSqlMapConfig.getSqlMapInstance();


Integer personId = 2222;
//Person.xml 안의 ID가 getPerson인 DB 선언에서 값이 psersonId(2222)인것을 select>해옴
Person person = (Person) sqlMap.queryForObject("getPerson",personId);

System.out.println("- Id : " + person.getId());

System.out.println("- name : " + person.getName());


System.out.println("\nSelect Done");
}

}




[바로가기 링크] : http://coolx.net/cboard/develop/418



Name
Password
Comment
Copyright © 1999-2017, swindler. All rights reserved. 367,611 visitor ( 1999.1.8-2004.5.26 ), 2,405,771 ( -2017.01.31)

  2HLAB   2HLAB_Blog   RedToolBox   Omil   Omil_Blog