Official document: mybatis official website
Several top-level elements in mapper:
- cache
- cache-ref
- resultMap
parameterMap- sql
- insert
- delete
- update
- select
SELECT
<select
id="selectPerson"
parameterType="int"
parameterMap="deprecated"
resultType="hashmap"
resultMap="personResultMap"
flushCache="false"
useCache="true"
timeout="10"
fetchSize="256"
statementType="PREPARED"
resultSetType="FORWARD_ONLY">
Note: only one of resulttype and resultmap can be selected.
Resulttype can be any wrapper type / entity class; resultmap is more powerful.
Let’s take a look at an article first: the difference between resulttype and resultmap
Flushcache: after calling SQL, clear the local cache and secondary cache. The default value is false.
Usecache: the secondary cache is saved after the call, and the default is true for select.
Statementtype: prepared | statement | callable, corresponding to the corresponding statement type respectively.
INSERT/DELETE/UPDATE
<insert
id="insertAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
keyColumn=""
useGeneratedKeys=""
keyProperty=""
timeout="20">
<update
id="updateAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
timeout="20">
<delete
id="deleteAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
timeout="20">
Secondary elements (tags under top level tags)
- foreach
<foreach item="item" collection="list" separator=",">
(#{item.username}, #{item.password}, #{item.email}, #{item.bio})
</foreach>
- selectKey
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
</selectKey>
- SQL defines reusable code fragments
definition
<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>
use
<select id="selectUsers" resultType="map">
select
<include refid="userColumns"><property name="alias" value="t1"/></include>,
<include refid="userColumns"><property name="alias" value="t2"/></include>
from some_table t1
cross join some_table t2
</select>
- Dynamic SQL (if, choose / when / otherwise, trim, where, set, bind)