Where The Streets Have No Name

ibatis정리 본문

Developement/Java

ibatis정리

highheat 2008. 7. 15. 19:41

[SqlMapConfig.xml 로딩]

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

Reader reader = Resources.getResourceAsReader("sql/SqlMapConfig.xml");
SqlMapClient client = SqlMapClientBuilder.buildSqlMapClient(reader);


소스 : src/sql/에 위치시키면 됨(eclipse상에서 소스위치로 설정된곳)

[count(*)같은 숫자값을 리턴받을경우]

<select id="selectCnt" resultClass="java.lang.Integer">
    select count(*) as cnt from UIP_EMPLOYEE
</select>

resultClass="java.lang.Integer" ->이부분이 핵심


int cnt = ((Integer)client.queryForObject("selectCnt")).intValue();


이렇게 받아서 사용하면 됨

[value object대신 hashmap으로 데이터를 받는경우]

<resultMap id="get-product-result" class="java.util.HashMap">
  <result property="num" column="NUM" />
  <result property="name" column="NAME" />
  <result property="birthdate" column="BIRTHDATE" />
  <result property="ssn" column="SSN" />
  <result property="sex" column="SEX" />
  <result property="telephone" column="TELEPHONE" />
  <result property="address" column="ADDRESS" />
  <result property="postal" column="POSTAL" />
</resultMap>

<select id="selectAllAccounts2" resultMap="get-product-result">
  select * from UIP_EMPLOYEE
</select>


List accountList2 = client.queryForList("selectAllAccounts2");

for(int i = 0;i < accountList2.size();i++){
    HashMap hm = new HashMap(); 
    hm = (HashMap)accountList2.get(i);
    System.out.println(hm.get("num")+","+hm.get("name")+""+hm.get("birthdate")+hm.get("telephone"));
}

[sql log:log4j]

# Global logging configuration
log4j.rootLogger=DEBUG, stdout, rolling

# SqlMap logging configuration...
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG

# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] -%m%n

# file output...
log4j.appender.rolling=org.apache.log4j.DailyRollingFileAppender
log4j.appender.rolling.File=C:/zk_pjt/log/output.log
log4j.appender.rolling.Append=true
log4j.appender.rolling.DatePattern='.'yyyy-MM-dd
log4j.appender.rolling.layout=org.apache.log4j.PatternLayout
log4j.appender.rolling.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n

위치: src -> eclipse상에서 프로젝트의 소스폴더

[조회]

<select id="selectEmployeeByNum" parameterClass="String" resultClass="hashmap">
        select * from UIP_EMPLOYEE where num = #num#
</select>

client.queryForList("selectEmployeeByNum", "10002");

[입력]

<insert id="insertEmployee2" parameterClass="hashmap">
        insert into uip_employee ( num, name, test ) values ( #num#, #name#, #test# )
</insert>


HashMap map = new HashMap();
map.put("num", "90009");
map.put("name", "아무개6");
map.put("test", new Integer(1));
client.insert("insertEmployee2", map);

[transaction]

SqlMapClient client = SqlMapFactory.getSqlMapInstance();

client.startTransaction();

try{
    HashMap map = new HashMap();
    map.put("num", "90009");
    map.put("name", "아무개6");
    map.put("test", new Integer(1));
    client.insert("insertEmployee2", map);


    map.clear();
    map.put("num", "90010");
    map.put("name", "아무개6");
    map.put("test", "xxx");
    client.insert("insertEmployee2", map); 
    client.commitTransaction()
}finally{
    client.endTransaction();
}

[SqlMapFactory]

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

import org.apache.log4j.*;

/**
 * <PRE>
 * ibatis의 sqlmapclient를 생성하는 singleton class
 *
 * </PRE>
 *
 */

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

    public static SqlMapClient getSqlMapInstance() {
        return sqlMap;
    }
}