Mybatis中如何优雅的接收DAO传递的参数:
1.当dao中传递单个或者多个参数时, 使用@Param(可以类比为别名)注解单一属性
dao示例:
User selectUser(@Param("userName") String name, @Param("deptId") int deptId);
xml文件示例:
<select id="selectUser" resultMap="UserResultMap">
select * from user
where user_name = #{userName} and dept_id = #{deptId}
</select>
如果没有使用@Param注解之后,xml如何获取参数
dao示例:
User selectUser(String name, int deptId);
xml文件示例:
<select id="demo" resultMap="User">
select *
from user where user_id=#{param0} and name= #{param1}
</select>
2.当dao中传递是一个数据实体时,直接在xml中通过属性名获取数据即可
public User selectUser(User user);
<select id="selectUser" parameterType="com.test.User" resultMap="UserResultMap">
select * from user
where user_name = #{userName} and dept_id = #{deptId}
</select>
parameterType:标明参数类型
resultMap:返回结果集
#{}里面的名称对应的是User类里面的成员属性。
3.当dao中传递是一个map时,直接在xml中通过key获取数据即可
dao示例:
List<AttrGroupEntity> selectPageByCatelogId(Map<String, Object> params);
xml示例:
<select id="selectPageByCatelogId" resultMap="attrGroupMap" parameterType="Map">
SELECT * FROM pms_attr_group
<where>
<if test="catelogId!=null and catelogId !=''">
catelog_id = #{catelogId}
</if>
<if test="key!=null and key != ''">
AND attr_group_id LIKE CONCAT('%', #{key},'%')
OR attr_group_name LIKE CONCAT('%',#{key},'%')
</if>
</where>
</select>
4.当dao中传递是一个list时,直接在xml中遍历list
dao示例:
boolean deleteAttrGroupByIds(List<Long> longs);
xml示例:
<delete id="deleteAttrGroupByIds" parameterType="java.util.List" >
DELETE FROM pms_attr_group WHERE attr_group_id IN
<foreach collection="list" open="(" item="id" close=")" index="index" separator=",">
${id}
</foreach>
</delete>
collection :collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合,我在上面传的参数为数组,所以值为list
item : 表示在迭代过程中每一个元素的别名
index :表示在迭代过程中每次迭代到的位置(下标)
open :前缀
close :后缀
separator :分隔符,表示迭代时每个元素之间以什么分隔
8252

被折叠的 条评论
为什么被折叠?



