Reusing SQL Fragments
we use the tags <sql></sql>and <include></include>. The <sql></sql>tag contains the fragment to reuse, the <include></include>tag includes such a fragment in a statement. For example:
- <sql id="selectItem_fragment">
- FROM items
- WHERE parentid = 6
- sql>
- <select id="selectItemCount" resultClass="int">
- SELECT COUNT(*) AS total
- <include refid="selectItem_fragment"/>
- select>
- <select id="selectItems" resultClass="Item">
- SELECT id, name
- <include refid="selectItem_fragment"/>
- select>
The fragments are included and processed on query-execution so parameters can be used too:
- <sql id="selectItem_fragment">
- FROM items
- WHERE parentid = #value#
- sql>
- <select id="selectItemCount" parameterClass="int" resultClass="int">
- SELECT COUNT(*) AS total
- <include refid="selectItem_fragment"/>
- select>
- <select id="selectItems" parameterClass="int" resultClass="Item">
- SELECT id, name
- <include refid="selectItem_fragment"/>
- select>
Auto-Generated Key
- >
- <insert id="insertProduct-ORACLE" parameterClass="com.domain.Product">
- <selectKey resultClass="int" >
- SELECT STOCKIDSEQUENCE.NEXTVAL AS ID FROM DUAL
- selectKey>
- insert into PRODUCT (PRD_ID,PRD_DESCRIPTION)
- values (#id#,#description#)
- insert>
The selectKey statement is executed before the insert statement if it is placed before the insert SQL, otherwise the selectKey statement is executed after the insert statement.
It improve in 2.0
- <insert id="insertProduct-ORACLE-type-specified" parameterClass="com.domain.Product">
- insert into PRODUCT (PRD_ID,PRD_DESCRIPTION)
- values (#id#,#description#)
- <selectKey resultClass="int" type="pre" >
- SELECT STOCKIDSEQUENCE.NEXTVAL AS ID FROM DUAL
- selectKey>
- insert>
Substitution Strings
select * from $tableName$
With this syntax, iBATIS will substitute the value of the “tableName” property into the SQL before the statement is prepared. With this support, you can substitute string into any part of an SQL statement.Important Note 1: This support will only substitute Strings, so it is not appropriate for complex data types like Date or Timestamp.
Important Note 2: If you use this support to alter a table name, or a column list, in an SQL select statement, then you should always specify remapResults=“true”.
iBATIS provides syntax for substituting strings into SQL before the statement is prepared. You can use this support to generate a dynamic SQL statement. An example of the substitution syntax is as follows: