From:http://ibatis.apache.org/docs/java/pdf/iBATIS-SqlMaps-2-Tutorial_en.pdf
Person.java
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 (테이블을 생성할 때만 참고하세요)
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 ( 주 설정 파일 )
<!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 접속 정보)
# 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 클래스의 매핑 정보; 맵파일 )
<!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"/>
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 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 ( 매핑 정보를 이용하여 매핑을 수행하는 객체를 생성하는 보조 클래스 )
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 를 선택하면 다음과 같은 결과를 확인할 수 있다.
'SQL > IBATIS' 카테고리의 다른 글
배치(Batches) (0) | 2014.02.19 |
---|---|
Data Mapper로 프로그래밍하기: The API (0) | 2014.02.19 |
ibatis 에서 iterate 사용 (insert select, union all) (0) | 2014.02.12 |
[본문스크랩] IBatis개발자 가이드 (0) | 2014.02.12 |
IBatis 시작하기 2 (0) | 2014.02.12 |
? and ? 와같은 ibatis 파라미터 두개로 처리하기 (0) | 2014.02.12 |
Ibatis 트렌젝션 사용시 유의점.. (0) | 2014.02.12 |
DynamicQuery 사용법 (0) | 2014.02.12 |