【MyBatis】映射器(1)
(1)select元素
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>
(2)insert元素
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})
(3)update元素
执行完成后会返回一个影响后的记录条数。
<update parameterType=”role” id=”updateRole”>
updatet_role set role_name = #{roleName} , note=#{note}
whereid=#{id}
</update>
(4)delete元素
执行完成后会返回一个影响后的记录条数。
<delete id=”delete”parameterType=”long”>
delete from t_role where id=#{id}
</delete>