Professional Documents
Culture Documents
iBATIS SqlMaps 2 - Ko
iBATIS SqlMaps 2 - Ko
Version 2.0
: (fromm0@gmail.com)
.
SQL Maps
. SQL Maps XML SQL statement .
SQL Maps . SQL Maps XML
SQL .
. SQL Maps SQL .
.?
SQL Maps , Map, (String, Integer) SQL XML
XML . .
1) (, Map ) . update
where .
2) statement . . SQL Maps
PreparedStatement .
statement ResultSet .
3) update rows . (single)
. , Map XML .
.
SQL Maps JAR . JVM
/WEB-INF/lib . .
http://java.sun.com/j2se/1.4/docs/tooldocs/win32/classpath.html
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ClassLoader.html
http://java.sun.com/j2se/1.4.2/docs/
iBATIS JAR .
File Name
ibatis-common.jar
Description
iBATIS Common Utilities
Required
YES
ibatis-sqlmap.jar
YES
ibatis-dao.jar
NO
JAR
. 2.0
. jdk1.4 Jakarta
Commons Logging . JAR /lib/optional .
. .
Description
When to Use
Directories
JDK1.4
Legacy JDK
Support
/lib/optional/jdbc
/lib/optional/jta /lib/optional/xml
JAR
.
iBATIS DAO(1.x)
iBATIS Backward
Compatibility
/lib/optional/compatibility
SQL Maps(1.x)
JAR
.
Runtime
Bytecode
Enhancement
(lazy)
DataSource
Implementation
Distributed
Caching
Logging Solution
Log4J
/lib/optional/enhancement
CGLIB2.0 bytecode
/lib/optional/dbcp
/lib/optional/caching
OSCache
/lib/optional/logging
1.x
.?
. .
1. 2.0 1.x . JAR
. . XML
. .
2. XML 2.0 . 1.x API .
. Ant XML
.
3. XML . .
.
4. . 1.x
. .
SQL Maps .
Ant build.xml .
<taskdef name="convertSqlMaps"
classname="com.ibatis.db.sqlmap.upgrade.ConvertTask"
classpathref="classpath"/>
<target name="convert">
<convertSqlMaps todir="D:/targetDirectory/" overwrite="true">
<fileset dir="D/sourceDirectory/">
<include name="**/maps/*.xml"/>
</fileset>
</convertSqlMaps>
</target>
Ant Ant .
.
JAR : .
() iBATIS .
. JAR
. JAR .
.
Old Files
New Files
ibatis-db.jar
ibatis-common.jar ()
1.2.9b 3
ibatis-sqlmap.jar ()
.
ibatis-common.jar
ibatis-dao.jar
ibatis-sqlmap.jar
ibatis-dao.jar (DAO
)
commons-logging-1-0-3.jar ()
commons-collections-2-1.jar ()
commons-logging.jar
commons-logging-api.jar
commons-collections.jar
commons-dbcp.jar
commons-pool.jar
oscache.jar
jta.jar
jdbc2_0-stdext.jar
xercesImpl.jar
xmlParserAPIs.jar
jdom.jar
commons-dbcp-1-1.jar ()
commons-pool-1-1.jar ()
oscache-2-0-1.jar ()
jta-1-0-1a.jar ()
jdbc2_0-stdext.jar ()
xercesImpl-2-4-0.jar ()
xmlParserAPIs-2-4-0.jar ()
xalan-2-5-2.jar ()
log4j-1.2.8.jar ()
cglib-full-2-0-rc2.jar ()
SQL Maps .
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/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 relative to the classpath and is completely optional. -->
<properties resource=" examples/sqlmap/maps/SqlMapConfigExample.properties " />
<!--These settings control SqlMapClient configuration details, primarily to do with transaction
management. They are all optional (more detail later in this document). -->
<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}"/>
<property name="JDBC.DefaultAutoCommit" value="true" />
<property name="Pool.MaximumActiveConnections" value="10"/>
<property name="Pool.MaximumIdleConnections" value="5"/>
<property name="Pool.MaximumCheckoutTime" value="120000"/>
<property name="Pool.TimeToWait" value="500"/>
<property name="Pool.PingQuery" value="select 1 from ACCOUNT"/>
<property name="Pool.PingEnabled" value="false"/>
<property name="Pool.PingConnectionsOlderThan" value="1"/>
<property name="Pool.PingConnectionsNotUsedFor" value="1"/>
</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="examples/sqlmap/maps/Person.xml" />
</sqlMapConfig>
SQL Maps .
<properties>
SQL Maps SQL Maps XML (name=value) <properties>
. SQL Maps
SQL Maps .
driver=org.hsqldb.jdbcDriver
SQL Maps SQL Maps ${driver} org.hsqldb.jdbcDriver
.
<property name="JDBC.Driver" value="${driver}"/>
.
. URL .
.
<properties url=file:///c:/config/my.properties />
<settings>
<settings> XML SqlMapClient . setting
. .
maxRequests
SQL .
. DBMS
. 10 maxTransactions
maxSessions maxTransactions .
.
:
maxRequests=256
maxSessions
Default: 512
.
SqlMapClient
.
maxTransaction maxRequests .
.
:
maxSessions=64
Default: 128
maxTransactions
SqlMapClient.startTransaction()
.
. DBMS . maxSessions
maxRequests .
.
:
maxTransactions=16
Default: 32
cacheModelsEnabled
SqlMapClient
. .
:
cacheModelsEnabled=true
Default: true (enabled)
lazyLoadingEnabled
SqlMapClient (lazy)
. .
:
lazyLoadingEnabled=true
Default: true (enabled)
enhancementEnabled
(lazy)
.
:
enhancementEnabled=true
Default: false (disabled)
<typeAlias>
typeAlias .
<typeAlias alias="shortname" type="com.long.class.path.Class"/>
SQL Maps alias .
Transaction Manager Aliases
JDBC
com.ibatis.sqlmap.engine.transaction.jdbc.JdbcTransactionConfig
JTA
com.ibatis.sqlmap.engine.transaction.jta.JtaTransactionConfig
EXTERNAL
com.ibatis.sqlmap.engine.transaction.external.ExternalTransactionConfig
Data Source Factory Aliases
SIMPLE
com.ibatis.sqlmap.engine.datasource.SimpleDataSourceFactory
DBCP
com.ibatis.sqlmap.engine.datasource.DbcpDataSourceFactory
<transactionManager>
1.0 : SQL Maps 1.0 . .
2.0 . /
SQL Maps .
<transactionManager> SQL Maps . type
. alias . 3 JDBC, JTA
EXTERNAL .
JDBC Connection commit() rollback() JDBC .
JTA SQL Maps
JTA . JNDI
UserTransaction . JNDI .
EXTERNAL .
.
SQL Maps . -( )
.
<dataSource>
dataSource SQL Maps
. 3
. DataSourceFactory .
SimpleDataSourceFactory
SimpleDataSource connection
(pooling) . iBATIS SimpleDataSource connection .
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="org.postgresql.Driver"/>
<property name="JDBC.ConnectionURL"
value="jdbc:postgresql://server:5432/dbname"/>
<property name="JDBC.Username" value="user"/>
<property name="JDBC.Password" value="password"/>
<!--OPTIONAL PROPERTIES BELOW -->
<property name="Pool.MaximumActiveConnections" value="10"/>
<property name="Pool.MaximumIdleConnections" value="5"/>
<property name="Pool.MaximumCheckoutTime" value="120000"/>
DbcpDataSourceFactory
DataSource API connection Jakarta DBCP (Database
Connection Pool) . DataSource / DataSource
standalone . DbcpDataSourceFactory
.
<transactionManager type="JDBC">
<dataSource type="DBCP">
<property name="JDBC.Driver" value="${driver}"/>
<property name="JDBC.ConnectionURL" value="${url}"/>
<property name="JDBC.Username" value="${username}"/>
<property name="JDBC.Password" value="${password}"/>
<!--OPTIONAL PROPERTIES BELOW -->
<property name="Pool.MaximumActiveConnections" value="10"/>
<property name="Pool.MaximumIdleConnections" value="5"/>
<property name="Pool.MaximumWait" value="60000"/>
<!--Use of the validation query can be problematic. If you have difficulty, try without it. -->
<property name="Pool.ValidationQuery" value="select * from ACCOUNT"/>
<property name="Pool.LogAbandoned" value="false"/>
<property name="Pool.RemoveAbandoned" value="false"/>
<property name="Pool.RemoveAbandonedTimeout" value="50000"/>
</datasource>
</transactionManager>
JndiDataSourceFactory
JNDI DataSource .
connection DataSource
. JDBC DataSource JNDI .
JndiDataSourceFactory JNDI DataSource .
.
<transactionManager type="JDBC" >
<dataSource type="JNDI">
<property name="DataSource"
value="java:comp/env/jdbc/jpetstore"/>
</dataSource>
</transactionManager>
JDBC . (global)
.
<transactionManager type="JTA" >
<property name="UserTransaction" value="java:/ctx/con/UserTransaction"/>
10
<dataSource type="JNDI">
<property name="DataSource"
value="java:comp/env/jdbc/jpetstore"/>
</dataSource>
</transactionManager>
UserTransaction JNDI UserTransaction .
SQL Maps JTA
.
<sqlMap>
sqlMap SQL Map SQL Map . SqlMapClient
SQL Map XML . SQL Map XML URL
(stream) . SQL Maps . .
<!--CLASSPATH RESOURCES -->
<sqlMap resource="com/ibatis/examples/sql/Customer.xml" />
<sqlMap resource="com/ibatis/examples/sql/Account.xml" />
<sqlMap resource="com/ibatis/examples/sql/Product.xml" />
<!--URL RESOURCES -->
<sqlMap url="file:///c:/config/Customer.xml " />
<sqlMap url="file:///c:/config/Account.xml " />
<sqlMap url="file:///c:/config/Product.xml" />
11
</sqlMap>
(Mapped) Statements
SQL Maps statement . statement SQL maps(input)
result maps(output) . statement result
. statement results .
<statement id=statementName
[parameterClass=some.class.Name]
[resultClass=some.class.Name]
[parameterMap=nameOfParameterMap]
[resultMap=nameOfResultMap]
[cacheModel=nameOfCache]
>
select * from PRODUCT where PRD_ID = [?|#propertyName#]
order by [$simpleDynamic$]
</statement>
statement [] .
<statement id=insertTestProduct >
12
Statement
<statement> SQL catch all statement.
statement . XML DTD
<statement> . statement
.
Statement Element
Attributes
Child Elements
Methods
<statement>
id
parameterClass
resultClass
parameterMap
resultMap
cacheModel
xmlResultName
<insert>
id
parameterClass
parameterMap
id
parameterClass
parameterMap
id
parameterClass
parameterMap
id
parameterClass
resultClass
parameterMap
resultMap
cacheModel
id
parameterClass
resultClass
parameterMap
resultMap
xmlResultName
<update>
<delete>
<select>
<procedure>
The SQL
SQL map . JDBC SQL .
statement .
SQL XML . greater-than
less-than .(<>). SQL XML . SQL
XML . XML CDATA
13
.
<statement id="getPersonsByAge" parameterClass=int resultClass="examples.domain.Person">
<![CDATA[
SELECT *
FROM PERSON
WHERE AGE > #value#
]]>
</statement>
(primay key) . RDBMS
. SQL Map <insert> <selectKey> . (pre-generated -
) (post-generated - MS-SQL ) . .
<!Oracle SEQUENCE Example -->
<insert id="insertProduct-ORACLE" parameterClass="com.domain.Product">
<selectKey resultClass="int" keyProperty="id" >
SELECT STOCKIDSEQUENCE.NEXTVAL AS ID FROM DUAL
</selectKey>
insert into PRODUCT (PRD_ID,PRD_DESCRIPTION)
values (#id#,#description#)
</insert>
<! Microsoft SQL Server IDENTITY Column Example -->
<insert id="insertProduct-MS-SQL" parameterClass="com.domain.Product">
insert into PRODUCT (PRD_DESCRIPTION) values (#description#)
<selectKey resultClass="int" keyProperty="id" >
SELECT @@IDENTITY AS ID
</selectKey>
</insert>
<procedure> statement .
.
<parameterMap id="swapParameters" class="map" >
<parameter property="email1" jdbcType="VARCHAR" javaType="java.lang.String" mode="INOUT"/>
<parameter property="email2" jdbcType="VARCHAR" javaType="java.lang.String"
mode="INOUT"/>
</parameterMap>
14
parameterClass
parameterClass ( ) . parameterClass
. statement
. parameterMap parameterClass .
examples.domain.Product .
<statement id=statementName parameterClass= examples.domain.Product>
insert into PRODUCT values (#id#, #description#, #price#)
</statement>
:
( ).
.
parameterClass (get/set)
.
parameterMap
parameterMap ( ) parameterMap . parameterMap parameterClass
. XML
parameterMap( ) .
! statement map .
parameterMap JDBC PreparedStatement .
:
<parameterMap id=insert-product-param class=com.domain.Product>
<parameter property=id/>
<parameter property=description/>
</parameterMap>
<statement id=insertProduct parameterMap=insert-product-param>
insert into PRODUCT (PRD_ID, PRD_DESCRIPTION) values (?,?);
</statement>
, map SQL (?) . ?
id description . map
.
15
.
statement . :
<statement id=insertProduct >
insert into PRODUCT (PRD_ID, PRD_DESCRIPTION)
values (#id#, #description#);
</statement>
#id# #description# . statement
. Product statement id description
. id=5 description=dog Product statement .
insert into PRODUCT (PRD_ID, PRD_DESCRIPTION)
values (5, dog);
resultClass
resultClass ( ) . resultClass
ResultSetMetaData JDBC ResultSet . ResultSet
. statement .
:
<statement id="getPerson" parameterClass=int resultClass="examples.domain.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#
</statement>
Person id, firstName, lastName, birthDate, weightInKilograms, heightInMeters
. SQL select .
. . Person
result set .
resultClass . .
ResultSetMetaData .
resultMap . Result maps .
resultMap
resultMap . resultMap
16
cacheModel
cacheModel cacheModel . cacheModel statement
. statement cacheModel . cacheModel
. statement .
<cacheModel id="product-cache" imlementation="LRU">
<flushInterval hours="24"/>
<flushOnExecute statement="insertProduct"/>
<flushOnExecute statement="updateProduct"/>
<flushOnExecute statement="deleteProduct"/>
<property name=size value=1000 />
</cacheModel>
<statement id=getProductList parameterClass=int cacheModel=product-cache>
select * from PRODUCT where PRD_CAT_ID = #value#
</statement>
WEAK products 24 update
(flush) .
xmlResultName
mapping result XML xmlResultName XML .
:
<select id="getPerson" parameterClass=int resultClass="xml" xmlResultName=person>
SELECT
PER_ID as id,
PER_FIRST_NAME as firstName,
17
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>
Maps
parameterMap statement .
parameterMaps
.
<parameterMap id=parameterMapName [class=com.domain.Product]>
<parameter property =propertyName [jdbcType=VARCHAR] [javaType=string]
[nullValue=NUMERIC] [null=-9999999]/>
<parameter />
<parameter />
</parameterMap>
[] . parameterMap statement id
. Class . Statement parameterClass class
.
<parameter>
parameterMap statement .
property .
property
map property statement (get) .
statement .
jdbcType
jdbcType . JDBC
.
18
jdbcType JDBC .
( blobs).
.
! null .
null .
javaType
javaType .
(reflection) . Map XML
. javaType
.
nullValue
nullValue ( ) . null null
. NULL (
null ). null ( int, double, float)
magic null . null NULL
.
<parameterMap>
parameterMap .
<parameterMap id=insert-product-param class=com.domain.Product>
<parameter property=id jdbcType=NUMERIC javaType=int nullValue=-9999999/>
<parameter property=description jdbcType=VARCHAR nullValue=NO_ENTRY/>
</parameterMap>
<statement id=insertProduct parameterMap=insert-product-param>
insert into PRODUCT (PRD_ID, PRD_DESCRIPTION) values (?,?);
</statement>
19
Maps
parameterMaps . Maps
(definition) .
statement . parameterMap statement
. ( Product)
.
<statement id=insertProduct parameterClass=com.domain.Product>
insert into PRODUCT (PRD_ID, PRD_DESCRIPTION)
values (#id#, #description#);
</statement>
.
<statement id=insertProduct parameterClass=com.domain.Product>
insert into PRODUCT (PRD_ID, PRD_DESCRIPTION)
values (#id:NUMERIC#, #description:VARCHAR#);
</statement>
null .
<statement id=insertProduct parameterClass=com.domain.Product>
insert into PRODUCT (PRD_ID, PRD_DESCRIPTION)
values (#id:NUMERIC:-999999#, #description:VARCHAR:NO_ENTRY#);
</statement>
! null .
.
20
! null
.
.
(String, Integer, Date) . :
<statement id=insertProduct parameter=java.lang.Integer>
select * from PRODUCT where PRD_ID = #value#
</statement>
PRD_ID . java.lang.Integer statement
. #value# Integer . value ( )
. Result Map result .
Result Map SQL Maps(API) .
. int java.lang.Integer .
Map result Map .
Map
Map( HashMap, TreeMap) . :
<statement id=insertProduct parameterClass=java.util.Map>
select * from PRODUCT
where PRD_CAT_ID = #catId#
and PRD_CODE = #code#
</statement>
statement . Map statement
Map catId code . Integer String
. Result Map result Map . Map
result Map SQL Map(API) .
Map . map java.util.Map .
Map result Map .
Result Maps
Result maps SQL Maps . resultMap statement
ResultSet . resultMap .
<resultMap id=resultMapName class=some.domain.Class [extends=parent-resultMap]>
<result property=propertyName column=COLUMN_NAME
[columnIndex=1] [javaType=int] [jdbcType=NUMERIC]
[nullValue=-999999] [select=someOtherStatement]
21
/>
<result />
<result />
<result />
</resultMap>
[] . resultMap statement id . resultMap
class . result
. Extends resultMap resultMap .
resultMap resultMap .
resultMap resultMap resultMap . /
resultMap .
resultMap ResultSet .
. , Map XML get/set
.
! Result Map .
property .
property
result map property statement result (get) .
results .
column
column ResultSet .
columnIndex
() columnIndex
ResultSet . 99%
. JDBC
.
jdbcType
jdbcType ResultSet
. result maps null Date
. Date SQL
dates( ) .
String VARCHAR, CHAR CLOB . .
22
javaType
javaType .
(reflection) . Map XML
. javaType
.
nullValue
nullValue NULL . ResultSet
NULL NULL nullValue . null
.
NULL result map
NULL .
<resultMap id=get-product-result class=com.ibatis.example.Product>
<result property=id column=PRD_ID/>
<result property=description column=PRD_DESCRIPTION/>
<result property=subCode column=PRD_SUB_CODE nullValue=-999/>
</resultMap>
PRD_SUB_CODE NULL subCode -999 .
NULL
. updates/inserts map nullValue
.
select
select . statement
statement . statement
statement property . .
/ .
Result Maps
resultMap statement
resultClass result map . result
set ( /)
. Product result map
statement .
<statement id=getProduct resultClass=com.ibatis.example.Product>
select
PRD_ID as id,
PRD_DESCRIPTION as description
23
from PRODUCT
where PRD_ID = #value#
</statement>
statement resultClass Product
. (required) . Result map . (tradeoff) (
) null( ) .
result map .
firstName firstname( ). result
map ( .). resultClass
. ResultSetMetaData JDBC
.
Map Results
Result Maps HashMap TreeMap Map . (Map List) collection
API(executeQueryForList() ) . Map
. Map key .
product Map .
<resultMap id=get-product-result class=java.util.HashMap>
<result property=id column=PRD_ID/>
<result property=code column=PRD_CODE/>
<result property=description column=PRD_DESCRIPTION/>
<result property=suggestedPrice column=PRD_SUGGESTED_PRICE/>
</resultMap>
HashMap Product . ( id) HashMap
. HashMap . Map result map .
24
:
<statement id=getProductCount resultClass=java.util.HashMap>
select * from PRODUCT
</statement>
ResultSet Map .
(Complex) Properties ( )
statement resultMap
( ) .
many side one side
1:1 1:M . :
<resultMap id=get-product-result class=com.ibatis.example.Product>
<result property=id column=PRD_ID/>
<result property=description column=PRD_DESCRIPTION/>
<result property=category column=PRD_CAT_ID select=getCategory/>
</resultMap>
<resultMap id=get-category-result class=com.ibatis.example.Category>
<result property=id column=CAT_ID/>
<result property=description column=CAT_DESCRIPTION/>
</resultMap>
<statement id=getProduct parameterClass=int resultMap=get-product-result>
select * from PRODUCT where PRD_ID = #value#
</statement>
<statement id=getCategory parameterClass=int resultMap=get-category-result>
select * from CATEGORY where CAT_ID = #value#
</statement>
Product Category category . Category
JDBC . statement
SQL Map . getProduct get-product-result result map
PRD_CAT_ID getCategory . get-category-result result map Category
. Category Product category .
25
.
<resultMap id=get-product-result class=com.ibatis.example.Product>
<result property=id column=PRD_ID/>
<result property=description column=PRD_DESCRIPTION/>
<result property=category.id column=CAT_ID />
<result property=category.description column=CAT_DESCRIPTION />
</resultMap>
<statement id=getProduct parameterClass=int resultMap=get-product-result>
select * from PRODUCT, CATEGORY where PRD_CAT_ID=CAT_ID and PRD_ID = #value#
</statement>
(Lazy) (1:1)
.
category . outer
null .
bytecode sub-select .
. .
. .
. .
separate select( )
.
Collection
. M:M 1:M
. statement . SQL Map
java.util.List java.util.Collection
. Category Product .(Category
java.util.List productList .)
<resultMap id=get-category-result class=com.ibatis.example.Category>
<result property=id column=CAT_ID/>
<result property=description column=CAT_DESCRIPTION/>
<result property=productList column=CAT_ID select= getProductsByCatId/>
</resultMap>
<resultMap id=get-product-result class=com.ibatis.example.Product>
<result property=id column=PRD_ID/>
<result property=description column=PRD_DESCRIPTION/>
</resultMap>
<statement id=getCategory parameterClass=int resultMap=get-category-result>
select * from CATEGORY where CAT_ID = #value#
</statement>
<statement id=getProductsByCatId parameterClass=int resultMap=get-product-result>
select * from PRODUCT where PRD_CAT_ID = #value#
</statement>
26
1:N M:N ? . .
( : SQL Maps 2.0.9 .)
column resultMap .
statement . statement
. #value#
. Column {param1=column1, param2=column2, ,
paramN=columnN} . PAYMENT Customer ID Order ID
.
<resultMap id=get-order-result class=com.ibatis.example.Order>
<result property=id column=ORD_ID/>
<result property=customerId column=ORD_CST_ID/>
27
resultMap=get-payment-result>
select * from PAYMENT
where PAY_ORD_ID = #itemId#
and PAY_CST_ID = #custId#
</statement>
.
{ORD_ID, ORD_CST_ID}
.
! SQL Map . / ()
. N+1 avoidance
result map .
JavaBean/Map
Property Mapping
Result Class /
Parameter Class***
Type Alias**
NO
YES
NO
YES
NO
YES
NO
YES
NO
YES
NO
YES
NO
YES
YES
boolean
boolean
byte
byte
short
short
int/integer
int/integer
long
long
float
float
double
double
string
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
28
java.util.Date
java.math.BigDecimal
* java.sql.Date
* java.sql.Time
* java.sql.Timestamp
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
date
decimal
N/A
N/A
N/A
Statement Results
statement result statement cacheModel .
SQL Map . cacheModel .
<cacheModel id="product-cache" type ="LRU" readOnly=true serialize=false>
<flushInterval hours="24"/>
<flushOnExecute statement="insertProduct"/>
<flushOnExecute statement="updateProduct"/>
<flushOnExecute statement="deleteProduct"/>
<property name=cache-size value=1000 />
</cacheModel>
LRU(Least Recently Used) product-cache .
type . flush
. 24 . interval hours, minutes, seconds milliseconds
. insertProduct, updateProduct, deleteProduct statement
. flush on execute . cache-size
. LRU .
statement .
<statement id=getProductList cacheModel=product-cache>
select * from PRODUCT where PRD_CAT_ID = #value#
</statement>
/
/ .
. .
( / ) . (retrieval) /
( ). readOnly=true .
(true).
29
. /
/ .
. .
. .
(lazy) . (lazy)
. (lazy) .
readOnly=false serialize=true
. .
. cacheModel type
. CacheController 4
. cacheModel property .
4 . .
MEMORY (com.ibatis.db.sqlmap.cache.memory.MemoryCacheController)
MEMORY . (garbage collector)
. MEMORY
.
MEMORY .
<cacheModel id="product-cache" type="MEMORY">
<flushInterval hours="24"/>
<flushOnExecute statement="insertProduct"/>
<flushOnExecute statement="updateProduct"/>
<flushOnExecute statement="deleteProduct"/>
<property name=reference-type value=WEAK />
</cacheModel>
MEMORY . reference-type STRONG, SOFT
WEAK . JVM .
MEMORY .
reachability java.lang.ref JDK .
WEAK
(default)
. .
. .
SOFT
.
.
30
STRONG
. 1)
, 2) , and 3) .
.
.
LRU (com.ibatis.db.sqlmap.cache.lru.LruCacheController)
LRU Least Recently Used( )
. .
. LRU
(
, .. ).
LRU .
<cacheModel id="product-cache" type="LRU">
<flushInterval hours="24"/>
<flushOnExecute statement="insertProduct"/>
<flushOnExecute statement="updateProduct"/>
<flushOnExecute statement="deleteProduct"/>
<property name=size value=1000 />
</cacheModel>
LRU . size
.
ArrayList .
.
FIFO (com.ibatis.db.sqlmap.cache.fifo.FifoCacheController)
FIFO First In First Out(
.) . . FIFO
. .
FIFO .
<cacheModel id="product-cache" type="FIFO">
<flushInterval hours="24"/>
<flushOnExecute statement="insertProduct"/>
<flushOnExecute statement="updateProduct"/>
<flushOnExecute statement="deleteProduct"/>
<property name=size value=1000 />
</cacheModel>
FIFO . . size
.
ArrayList .
.
31
OSCACHE (com.ibatis.db.sqlmap.cache.oscache.OSCacheController)
OSCACHE OSCache 2.0 . .
OSCACHE .
<cacheModel id="product-cache" type="OSCACHE">
<flushInterval hours="24"/>
<flushOnExecute statement="insertProduct"/>
<flushOnExecute statement="updateProduct"/>
<flushOnExecute statement="deleteProduct"/>
</cacheModel>
OSCACHE . OSCache
oscache.properties . , , (,
) .
OSCache . OSCache Open Symphony
.
http://www.opensymphony.com/oscache/
Statements
JDBC SQL.
SQL . if-else
.
. SQL Map API statement .
.
<select id="dynamicGetAccountList"
cacheModel="account-cache"
resultMap="account-result" >
select * from ACCOUNT
<isGreaterThan prepend="and" property="id" compareValue="0">
where ACC_ID = #id#
</isGreaterThan>
order by ACC_LAST_NAME
</select>
id statement .
0 statement .
select * from ACCOUNT where ACC_ID = ?
0 statement .
32
33
. true
SQL .
:
prepend statement SQL()
property ()
compareProperty ( compareValue)
compareValue ( compareProperty)
<isEqual>
<isNotEqual>
<isGreaterThan>
<isGreaterEqual>
<isLessThan>
<isLessEqual>
.
.
:
<isLessEqual prepend=AND property=age
compareValue=18> ADOLESCENT = TRUE
</isLessEqual>
.
:
prepend
property
statement
<isPropertyAvailable>
( .)
<isNotPropertyAvailable>
( .)
<isNull>
null
<isNotNull>
<isEmpty>
null
Collection, String.valueOf() null empty( or
34
SQL()
()
size() < 1)
<isNotEmpty>
Parameter Present:
Parameter Present Attributes:
prepend the statement SQL()
<isParameterPresent>
(not null) .
<isNotParameterPresent>
(null) .
Example Usage:
<isNotParameterPresent prepend=AND>
EMPLOYEE_TYPE = DEFAULT
</isNotParameterPresent>
Iterate: collection .
Iterate Attributes:
prepend the statement SQL()
property java.util.List ()
open , . ()
close , . ()
conjunction , AND OR . ()
<iterate>
java.util.List
:
<iterate prepend=AND property=userNameList
open=( close=) conjunction=OR>
username=#userNameList[]#
</iterate>
: iterator []
.
.
35
SQL
statement API SQL
. SQL statement statement
SQL . maps . .
.
<statement id=getProduct resultMap=get-product-result>
select * from PRODUCT order by $preferredOrder$
</statement>
preferredOrder ( map) preferredOrder
. SQL statement . .
SQL , . SQL
.
. JSP
.
<statements> SQL statement
.
<statement id=getProduct resultMap=get-product-result>
SELECT * FROM PRODUCT
<dynamic prepend=WHERE>
<isNotEmpty property=description>
PRD_DESCRIPTION $operator$ #description#
</isNotEmpty>
</dynamic>
</statement>
operator $operator$ . operator
;like description %dog% SQL .
SELECT * FROM PRODUCT WHERE PRD_DESCRIPTION LIKE %dog%
36
! . .startTransaction() commit()
rollback() . SqlMapClient
.
! SqlMapClient ThreadLocal .
startTransaction() Connection .
connection ( connection ) commitTransaction() endTransaction()
37
. pool connection .
( )
. startTransaction(), commitTransaction() endTransaction()
statement
.
private Reader reader =
new Resources.getResourceAsReader ("com/ibatis/example/sqlMap-config.xml");
private SqlMapClient sqlMap = XmlSqlMapBuilder.buildSqlMap(reader);
public updateItemDescription (String itemId, String newDescription)
throws SQLException {
try {
Item item = (Item) sqlMap.queryForObject ("getItem", itemId);
item.setDescription (TX1);
//No transaction demarcated, so transaction will be automatic (implied)
sqlMap.update ("updateItem", item);
item.setDescription (newDescription);
item.setDescription (TX2);
//No transaction demarcated, so transaction will be automatic (implied)
sqlMap.update("updateItem", item);
} catch (SQLException e) { throw (SQLException) e.fillInStackTrace(); }
}
! . update
. updateItem item description
TX1 description .( .)
()
SQL Maps .
( JTA ) update .( update
.)
/
(-( )) EJB
. EJB EJB .
. SQL Map
<transactionManager> type EXTERNAL .
SQL Map . , ,
. SqlMapClient startTransaction(), commitTransaction() endTransaction()
.
. Connection pool connection .
.
38
SQL Map .
SQL Map .
SQL Map <transactionManager> type JTA UserTransaction SqlMapClient
UserTransaction JNDI . <transactionManager>
.
. . .
try {
orderSqlMap.startTransaction();
storeSqlMap.startTransaction();
orderSqlMap.insertOrder();
orderSqlMap.updateQuantity();
storeSqlMap.commitTransaction();
orderSqlMap.commitTransaction();
} finally {
try {
storeSqlMap.endTransaction()
} finally {
orderSqlMap.endTransaction()
}
SqlMapClient .
SqlMapClient(orderSqlMap) . ,
SqlMapClient(orderSqlMap) commitTransaction() endTransaction()
. .
! .
.
. EJB EJB
. SQL Map
JPetStore www.ibatis.com .
(Batches)
statement(insert/update/delete)
JDBC .
SQL Map API . .
sqlMap.startBatch();
//execute statements in between
39
sqlMap.executeBatch();
40
statement . <statement>
name . . null
. .
insert(), update(), delete() : update statement .
update statement . .
executeUpdate() statement row .
queryForObject() : executeQueryForObject() .
. statement
.
queryForList() : queryForList() .
( ) .
. row
. rows result row .
RowHandler . row RowHandler
. RowHandler .
public void handleRow (Object object, List list);
row RowHandler .
. RowHandler .
queryForList() List . result ,
. 100 row
.
queryForPaginatedList(): ,
.
. 10,000 100 . PaginatedList
(nextPage(), previousPage(), gotoPage()) (isFirstPage(), isMiddlePage(),
isLastPage(), isNextPageAvailable(), isPreviousPageAvailable(), getPageIndex(), getPageSize()) .
PaginatedList
statement . PaginatedList
.
queryForMap(): collection . keyProperty
(key) map . Employee collection
employeeNumber (key) map . Map employee
valueProperty employee .
employee (key) employee map . result Map
. result Map .
41
sqlMap.commitTransaction();
Example 2: . (select)
sqlMap.startTransaction();
Integer key = new Integer (1);
Example 3: result .
sqlMap.startTransaction();
Example 4: . (select)
sqlMap.startTransaction();
List list = sqlMap.queryForList (getProductList, null);
sqlMap.commitTransaction();
Example 5:
// When startTransaction is not called, the statements will
// auto-commit. Calling commit/rollback is not needed.
int rows = sqlMap.insert (insertProduct, product);
42
Example 6: .
sqlMap.startTransaction();
List list = sqlMap.queryForList (getProductList, null, 0, 40);
sqlMap.commitTransaction();
sqlMap.commitTransaction();
Example 8: . (select)
PaginatedList list =
sqlMap.queryForPaginatedList (getProductList, null, 10);
list.nextPage();
list.previousPage();
Example 9: map .
sqlMap.startTransaction();
Map map = sqlMap.queryForMap (getProductList, null, productCode);
sqlMap.commitTransaction();
43
Log
commons ( log4j.properties) JAR(
log4j.jar) . Log4J
. .
1: Log4J JAR .
Log4J JAR .
Commons Logging API. . Log4J
JAR . URL Log4J
iBATIS JAR . WEB-INF/lib
log4j.jar . standalone JVM .
2: Log4J
Log4J . Commons Logging properties .
log4j.properties .
log4j.properties
44
8 #log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
9 #log4j.logger.java.sql.Connection=DEBUG
10 #log4j.logger.java.sql.Statement=DEBUG
11 #log4j.logger.java.sql.PreparedStatement=DEBUG
12 #log4j.logger.java.sql.ResultSet=DEBUG
13
14 # Console output...
15 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
16 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
17 log4j.appender.stdout.layout.ConversionPattern=%5p [%t] -%m%n
SqlMaps . SqlMap API .
.
.?
. getting setting .
( ) . set (
setEngine). get ( getEngine). Boolean
45
is ( isEngineRunning). Set .
( String) . Get
. . Serializable .
. SQL Map
.
.
public class Product implements Serializable {
private String id;
private String description;
public String getId() {
return id;
}
public void setId(String id) {
}
this.id = id;
! getXxxx() setXxxx() .
. .
Okay,
46
Resources (com.ibatis.common.resources.*)
Resources . ClassLoaders
/ . Resource
.
:
Reader :
Stream :
File : /
Properties :
URL :
Resource ( ).
Reader getResourceAsReader(String resource);
Stream getResourceAsStream(String resource);
File getResourceAsFile(String resource);
Properties getResourceAsProperties(String resource);
Url getResourceAsUrl(String resource);
ClassLoader Resource .
. ClassLoader (
) ClassLoader( ClassLoader
) . ClassLoader (sister) .
47
.
Reader getResourceAsReader (ClassLoader classLoader, String resource);
Stream getResourceAsStream (ClassLoader classLoader, String resource);
File getResourceAsFile (ClassLoader classLoader, String resource);
Properties getResourceAsProperties (ClassLoader classLoader, String resource);
Url getResourceAsUrl (ClassLoader classLoader, String resource);
resource / .
com.domain.mypackage.MyPropertiesFile.properties
Resource .( / .)
String resource = com/domain/mypackage/MyPropertiesFile.properties;
Properties props = Resources.getResourceAsProperties (resource);
Reader SqlMap .
(properties.sqlMap-config.xml).
String resource = properties/sqlMap-config.xml;
Reader reader = Resources.getResourceAsReader(resource);
SqlMapClient sqlMap = XmlSqlMapBuilder.buildSqlMap(reader);
SimpleDataSource (com.ibatis.common.jdbc.*)
SimpleDataSource JDBC 2.0 DataSource . connection pooling
connection pooling . SimpleDataSource JDBC
DataSource URL JDBCAPI(JDBC Standard Extensions API)
.
http://java.sun.com/products/jdbc/jdbc20.stdext.javadoc/
Required
Default
JDBC.Driver
Yes
n/a
JDBC.ConnectionURL
Yes
n/a
JDBC
JDBC connection URL.
JDBC.Username
Yes
n/a
JDBC.Password
JDBC.DefaultAutoCommit
Yes
No
n/a
driver
dependant
48
Description
Pool connection
autocommit
Pool.MaximumActiveConnections
No
10
connection
Pool.MaximumIdleConnections
No
Pool.MaximumCheckoutTime
No
20000
Pool.TimeToWait
No
20000
connection
connection
.
connection pool
.
.( .)
Pool.PingQuery
No
n/a
ping connection
. Connection
pool
connection ping
.
. ping
.
Pool.PingEnabled
No
false
Pool.PingConnectionsOlderThan
No
(milliseconds )
connection .
( 12)
connection
.
Pool.PingConnectionsNotUsedFor
No
connection ping
.
connection .
Driver.*
No
N/A
JDBC
.
JDBC
Driver
.
compressionEnabled
Driver.compressionEnabled=true
SimpleDataSource .
: dao.xml SqlMap-
49
config.xml .
: SimpleDataSource
DataSource dataSource = new SimpleDataSource(props); //properties usually loaded from a file
Connection conn = dataSource.getConnection();
//..database queries and updates
conn.commit();
conn.close(); //connections retrieved from SimpleDataSource will return to the pool when closed
ScriptRunner (com.ibatis.common.jdbc.*)
ScriptRunner
SQL . ScriptRunner
.
: initialize-db.sql
1: connection
Connection conn = getConnection(); //some method to get a Connection
ScriptRunner runner = new ScriptRunner ();
runner.runScript(conn, Resources.getResourceAsReader("com/some/resource/path/initialize.sql"));
conn.close();
2: connection
50
2: connection
Properties props = getProperties (); // some properties from somewhere
ScriptRunner runner = new ScriptRunner (props);
runner.runScript(conn, new FileReader("/usr/local/db/scripts/ initialize-db.sql"));
(Map) .
driver=org.hsqldb.jdbcDriver
url=jdbc:hsqldb:.
username=dba
password=whatever
stopOnError=true
:
// if you want the script runner to stop running after a single error
scriptRunner.setStopOnError (true);
// if you want to log output to somewhere other than System.out
scriptRunner.setLogWriter (new PrintWriter());
CLINTON BEGIN MAKES NO WARRANTIES, EXPRESS OR IMPLIED, AS TO THE INFORMATION IN THIS DOCUMENT.
2004 Clinton Begin. All rights reserved. iBATIS and iBATIS logos are trademarks of Clinton Begin.
The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
51