Ibatis 시작하기 -1-

SQL/IBATIS 2014. 2. 12. 20:56
728x90
반응형

From:http://ibatis.apache.org/docs/java/pdf/iBATIS-SqlMaps-2-Tutorial_en.pdf


Person.java

package test;

public class Person {
 private int id;
 private String firstName;
 private String lastName;
 private java.sql.Date birthDate;
 private double weightInKilograms;
 private double heightInMeters;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public java.sql.Date getBirthDate() {
  return birthDate;
 }
 public void setBirthDate(java.sql.Date birthDate) {
  this.birthDate = birthDate;
 }
 public double getWeightInKilograms() {
  return weightInKilograms;
 }
 public void setWeightInKilograms(double weightInKilograms) {
  this.weightInKilograms = weightInKilograms;
 }
 public double getHeightInMeters() {
  return heightInMeters;
 }
 public void setHeightInMeters(double heightInMeters) {
  this.heightInMeters = heightInMeters;
 }
}


Person.sql (테이블을 생성할 때만 참고하세요)

CREATE TABLE PERSON(
   PER_ID NUMBER (5, 0) NOT NULL,
   PER_FIRST_NAME VARCHAR (40) NOT NULL,
   PER_LAST_NAME VARCHAR (40) NOT NULL,
   PER_BIRTH_DATE DATE ,
   PER_WEIGHT_KG NUMBER (4, 2) NOT NULL,
   PER_HEIGHT_M NUMBER (4, 2) NOT NULL,
   PRIMARY KEY (PER_ID)
);
insert into person values(1, 'Chalie', 'Whisky', sysdate, 50, 20);


WEB-INF/classes/SqlMapConfigExample.xml ( 주 설정 파일 )

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<!-- Always ensure to use the correct XML header as above! -->

<sqlMapConfig>
<!-- The properties (name=value) in the file specified here can be used placeholders in this config
file (e.g. “${driver}”. The file is usually relative to the classpath and is optional. -->

<properties resource="SqlMapConfigExample.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="Person.xml" />

</sqlMapConfig>


WEB-INF/classes/SqlMapConfigExample.properties (주 설정파일에 등록되는 DB 접속 정보)

# This is just a simple properties file that simplifies automated configuration
# of the SQL Maps configuration file (e.g. by Ant builds or continuous
# integration tools for different environments… etc.)
# These values can be used in any property value in the file above (e.g. “${driver}”)
# Using a properties file such as this is completely optional.
driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:ORCL
username=scott
password=tiger


WEB-INF/classes/Person.xml ( 주 설정파일에 등록되는 TABLE 과 Bean 클래스의 매핑 정보; 맵파일 )

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Person">

  <!-- Use type aliases to avoid typing the full classname every time. -->
  <typeAlias alias="Person" type="test.Person"/>
  <!-- Result maps describe the mapping between the columns returned
       from a query, and the class properties.  A result map isn't
       necessary if the columns (or aliases) match to the properties
       exactly. -->

  <resultMap id="PersonResult" class="Person">
    <result property="id" column="PER_ID"/>
    <result property="firstName" column="PER_FIRST_NAME"/>
    <result property="lastName" column="PER_LAST_NAME"/>
    <result property="birthDate" column="PER_BIRTH_DATE"/>
    <result property="weightInKilograms" column="PER_WEIGHT_KG"/>
    <result property="heightInMeters" column="PER_HEIGHT_M"/>
  </resultMap>
  <!-- Select with no parameters using the result map for Account class. -->

  <select id="selectAllPerson" resultMap="PersonResult">
    select * from PERSON
  </select>


<!-- Use primitive wrapper type (e.g. Integer) as parameter and allow results to
be auto-mapped results to Person object (JavaBean) properties. A simpler select example without the result map.  Note the aliases to match the properties of the target result class. -->

<select id="getPerson" parameterClass="int" resultClass="Person">
   SELECT
      PER_ID as id,
      PER_FIRST_NAME as firstName,
      PER_LAST_NAME as lastName,
      PER_BIRTH_DATE as birthDate,
      PER_WEIGHT_KG as weightInKilograms,
      PER_HEIGHT_M as heightInMeters
      FROM PERSON
   WHERE PER_ID = #value#
</select>

<!-- Use Person object (JavaBean) properties as parameters for insert. Each of the
parameters in the #hash# symbols is a JavaBeans property. -->

<insert id="insertPerson" parameterClass="Person">
   INSERT INTO
      PERSON (PER_ID, PER_FIRST_NAME, PER_LAST_NAME,
      PER_BIRTH_DATE, PER_WEIGHT_KG, PER_HEIGHT_M)
      VALUES (#id#, #firstName#, #lastName#, #birthDate#, #weightInKilograms#, #heightInMeters#)
</insert>

<!-- Use Person object (JavaBean) properties as parameters for update. Each of the
parameters in the #hash# symbols is a JavaBeans property. -->

<update id="updatePerson" parameterClass="Person">
   UPDATE PERSON
      SET PER_FIRST_NAME = #firstName#,
      PER_LAST_NAME = #lastName#, PER_BIRTH_DATE = #birthDate#,
      PER_WEIGHT_KG = #weightInKilograms#,
      PER_HEIGHT_M = #heightInMeters#
   WHERE PER_ID = #id#
</update>

<!-- Use Person object (JavaBean) “id” properties as parameters for delete. Each of the
parameters in the #hash# symbols is a JavaBeans property. -->

<delete id="deletePerson" parameterClass="Person">
   DELETE PERSON
      WHERE PER_ID = #id#
</delete>

</sqlMap>


MyAppSqlConfig.java ( 매핑 정보를 이용하여 매핑을 수행하는 객체를 생성하는 보조 클래스 )

package test;

public class MyAppSqlConfig {
  private static final SqlMapClient sqlMap; // Table과 Bean사이의 매핑을 담당하는 클래스 인스턴스
  static {
     try {
       String resource = “SqlMapConfigExample.xml”; // 주설정 파일
       Reader reader = Resources.getResourceAsReader (resource);
       sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); //주설정파일을 읽어 들인다.
     } catch (Exception e) {
       // If you get an error at this point, it doesn’t matter what it was. It is going to be
       // unrecoverable and we will want the app to blow up hard so we are aware of the
       // problem. You should always log such errors and re-throw them in such a way that
       // you can be made immediately aware of the problem.
       e.printStackTrace();
       throw new RuntimeException (“Error initializing MyAppSqlConfig class. Cause: ” + e);
     }
  }
  public static SqlMapClient getSqlMapInstance () {
    return sqlMap;
  }
}


사용법은 아래 참조

SqlMapClient sqlMap = MyAppSqlMapConfig.getSqlMapInstance(); // as coded above
...
List list = sqlMap.queryForList("selectAllPerson"); //다수개의 레코드를 가져오는 경우


Integer personPk = new Integer(5);
Person person = (Person) sqlMap.queryForObject (“getPerson”, personPk); // 한개의 레코드를 가져오는 경우

public object QueryForObject(string statementName) 메소드는 쿼리 문장에 파라미터가 없는 경우에 사용된다.

person.setHeightInMeters(1.83); // person as read above
person.setWeightInKilograms(86.36);

sqlMap.update(“updatePerson”, person);

If we wanted to delete this Person, it’s just as easy.

sqlMap.delete (“deletePerson”, person);

Inserting a new Person is similar.
Person newPerson = new Person();
newPerson.setId(11); // you would normally get the ID from a sequence or custom table
newPerson.setFirstName(“Clinton”);
newPerson.setLastName(“Begin”);
newPerson.setBirthDate (null);
newPerson.setHeightInMeters(1.83);
newPerson.setWeightInKilograms(86.36);

sqlMap.insert (“insertPerson”, newPerson);

WEB-INF/class/IBatisTestServlet.java

import java.io.*;
import javax.servlet.http.*;

import test.MyAppSqlConfig;
import test.Person;

import com.ibatis.sqlmap.client.SqlMapClient;

 public class IBatisTestServlet extends javax.servlet.http.HttpServlet {


 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException  {
  PrintWriter out = response.getWriter();
  SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance();
  try{
   Integer personPk = new Integer(1);
   Person person = (Person) sqlMap.queryForObject ("getPerson", personPk);
   out.print("sqlMap.queryForObject(\"getPerson\", personPk)-->");
   out.println(person.getFirstName()+"<p>");

   java.util.List  list = sqlMap.queryForList ("selectAllPerson");
   out.print("sqlMap.queryForList(\"selectAllPerson\")-->");
   for(int i=0;i<list.size();i++) {
     Person p = (Person)list.get(i);
     out.print(p.getFirstName()+", " + p.getLastName());
   }
  }catch(Exception e){
   out.println(e);
  }     
 }
 }


 위의 파일을 이용하여 iBATIS를 테스트하기 위한 설정은 다음 그림과 같다.

 


위와같이 설정한 후에 Run As > Run On Server > JBoss 4.2 를 선택하면 다음과 같은 결과를 확인할 수 있다.

728x90
반응형
블로그 이미지

nineDeveloper

안녕하세요 현직 개발자 입니다 ~ 빠르게 변화하는 세상에 뒤쳐지지 않도록 우리모두 열심히 공부합시다 ~! 개발공부는 넘나 재미있는 것~!

,