1. Ibatis参数类型
设有一张用户表user,字段id、user_name、password,与之对应的DO:
UserDO {
Long id;
String userName;
String password;
};
(1) 内联参数映射
<insert id=”User.insert”>
insert intouser (
id,
user_name,password
) values (
#id : BIGINT#,
#userName :VACHAR#,
#password: VACHAR#
)
</select>
(2) 外部参数映射
<resultMap id=”baseResultMap” class=”com.org.UserDO”>
<result column=”id” property=”id”jdbcType=”BIGINT”/>
<result column=”user_name” property=”userName”jdbcType=”VARCHAR”>
<result column=”password” property=”password”jdbcType=”VARCHAR”>
</resultMap>
<insert id=”User.insert” parameterMap=” baseResultMap”>
insert intouser (
id, user_name, password
) values (
#id#,
#userName#,
#password#
)
<select>
当有多个映射语句时,外联参数映射书写更容易使用。
2. 生成主键
通常插入一个一条数据时,可以通过一下方式生成主键:
(1) 将数据插入数据库中并且数据库为该记录生成了主键之后,就立即抓取该键值。
(2) 在插入记录之前就获取键值,即插入记录之前先分配一个键值。这种策略可以避免多线程同时插入数据并在记录插入之后才能获取键值所带来的潜在危险。
与之相对应的,在我们的系统中都有体现:
(1) 利用Ibatis中的selectKey元素:
<insertid="bmPlay.insert" parameterClass="bmPlayDO">
insert into bm_play (gmt_create, gmt_modified, name, playid,···) values(now(), now(), #name#, #playid#,···)
<selectKey resultClass="long"keyProperty="id">
selectlast_insert_id() as id
</selectKey>
</insert>
(2) 先生成id,然后再将记录插入到数据库中。
privateGroupSequence applicationMonitorSequence;
longapplicationMonitorId = applicationMonitorSequence.nextValue();
利用类GroupSequence来为每个要插入的记录分配id。
3. 数据分页查询
数据分页查询包括前段分页显示查询数据结果和分页查询数据库中的数据。为实现前段数据分页显示可以:(1) 一次性查询出所有符合条件的数据,前段将数据分页展示;(2) 每次只查询一页数据,需要某页数据时再进行查询。显然,第二种方式较好。选择第二种需要单独查询数据库中满足该条件的数据总条数。
3.1 MySql数据库分页查询
MySql数据库中提供了limit函数,一般写在sql语句后面就可以了。limit子句用来限制由select语句返回结果的数量,第一个参数为第一行在所有数据中的位置(从0开始,省略表示从0开始),第二个参数指定最多结果个数。例如:
select * fromtable where … limit 5; #返回前5行
select * fromtable where … limit 0,10;#返回前10行
select * fromtable where … limit 10,20;#返回第10行开始的20行数据
3.2 对应的Ibatis
由上可知,只要我们在对应的select中加上limit限制条件即可,在我们的系统中表现如下:
<select id="GroupDAO.query"resultMap="BaseResultMap" parameterClass =
"GroupQuery">
select
id,
name,
description,
···
from
bm_group_new a
where a.status = 1
<isNotNull prepend="and"property="groupId">
a.id=#groupId#
</isNotNull>
<isNotNull prepend="and"property="name">
a.name like CONCAT('%', #name#,'%')
</isNotNull>
<isNotNull prepend="and"property="departId">
a.depart_id = #departId#
</isNotNull>
···
order by a.id
<dynamicprepend="">
<isNotEqualprepend="" property="pageSize"compareValue="-1">
limit#pageFristItem#, #pageSize#
</isNotEqual>
</dynamic>
</select>
</sqlMap>
显然在使用这种分页查询的时候,需要传递limit的两个参数:查询的首行以及返回的查询结果总行数。