A:配置
<select id=」countFirstName」parameterType=」string」 resultType=」int」>
select count(*) as total from t_user where name like concat(#{firstName},’%’)
</select>
在接口UserDao中定義方法:
public int countFilrstName(String firstName);
B:自動映射
參數:autoMappingBehavior,不設置爲NONE的時候,MyBatis會提供自動映射的功能,只要返回的SQL列名和JavaBean的屬性一致,Mybatis就會幫助我們回填這些字段無需任何配置。
自動映射在settings元素中配置autoMappingBehavior,包含3個值:
NONE:取消自動映射
PARTIAL:只會自動映射,沒有定義嵌套結果集映射的結果集。(默認值)
FULL:會自動映射任意複雜的結果集(無論是否嵌套)(嵌套映射)
C:傳遞多個參數
1、 使用Map傳遞參數(不推薦)
<select id=」findRoleByMap」 parameterType=」map」 resultMap = 「roleMap」>
select id, role_name , note from t_role
where role_namelike concat(‘%’ ,#{roleName},’%’)
and note likeconcat(‘%’, #{note} , ‘%’)
</select>
RoleDao接口中:
public List<Role> findRoleByMap(Map<String,String>params);
參數設置
Map<String, String> paramsMap = new HashMap<String ,String>();
paramsMap.put(「roleName」, 「me」);
paramsMap.put(「note」,」te」);
roleMapper.findRoleByMap(paramsMap);
2、 使用註解方式傳遞參數
RoleDao接口:
public List<Role> findRoleByMap(@Param(「roleName」)String rolename,@Param(「note」) String note);
配置文件:
<select id=」findRoleByMap」 resultMap = 「roleMap」>
select id, role_name , note from t_role
where role_namelike concat(‘%’ ,#{roleName},’%’)
and note likeconcat(‘%’, #{note} , ‘%’)
</select>
3、 使用JavaBean傳遞參數
RoleDao接口:
public List<Role> findRoleByMap(RoleParam params);
配置文件:
<select id=」findRoleByMap」parameterType=」com.lwt.RoleParam」 resultMap = 「roleMap」>
select id, role_name , note from t_role
whererole_name like concat(‘%’ ,#{roleName},’%’)
and notelike concat(‘%’, #{note} , ‘%’)
</select>
D:使用resultMap映射結果集
<selectparameterType=」long」 id = 「getRole」resultMap =」roleResultMap」>
selectid ,role_name , note from t_role whereid=#{id}
</select>
<resultMapid=」roleResultMap」 type=」com.lwt.Role」>
<id property=」id」 column=」id」 /> 指定主鍵
<result property=」roleName」 column=」role_name」/>
<result property=」note」 column=」note」/>
</resultMap>
A:配置
<insert parameterType=」role」 id=」insertRole」>
insert into t_role(role_name , note) values(#{roleName},#{note})
</insert>
B:主鍵回填和自定義
keyProperty:指定哪個是主鍵字段
useGeneratedKeys:告訴Mybatis這個主鍵是否使用數據庫內置策略生成
方式一:在數據庫中指定表id設置規則
<insertid=」insertRole」 parameterType=」role」
useGeneratedKeys=」true」 keyProperty=」id」>
insert into t_role(role_name , note) values(#{roleName},#{note})
</insert>
說明:在t_role指定了主鍵自增長,因此插入時會回填JavaBean的id值。
方式二:自定義規則(無數據設置id爲1,否則取最大id加2)(MySql中)
<insertid=」insertRole」 parameterType=」role」 useGeneratedKeys=」true」 keyProperty=」id」>
<selectKey keyProperty=」id」 resultType=」int」 order=」BEFORE」>
selectif( max(id) is null , 1 , max(id) +2) as newIdfrom t_role
</selectKey>
</insert>insert into t_role(role_name ,note) values(#{roleName},#{note})
執行完成後會返回一個影響後的記錄條數。
<update parameterType=」role」 id=」updateRole」>
updatet_role set role_name = #{roleName} , note=#{note}
whereid=#{id}
</update>
執行完成後會返回一個影響後的記錄條數。
<delete id=」delete」parameterType=」long」>
delete from t_role where id=#{id}
</delete>