一、单个参数传入
public List<Message> queryMessageList1(String command);
<select id="queryMessageList1" parameterType="java.lang.String" resultMap="MessageResult">
select id,command,description,content from message where and command=#{command}
</select>
传入基本数据类中的时候parameterType="java.lang.String" 这种基本数据类型的时候不能使用if 或其他标签判断command是否存在如下这种做法是错误的,应为string中没有getCommnad方法,如果要使用下边这种方式可以考虑将其封装到某个类中并提供相应的getter setter方法
<select id="queryMessageList1" parameterType="java.lang.String" resultMap="MessageResult">
select id,command,description,content from message
<where>
<if test="command != null and !"".equals(command.trim())">
and command=#{command}
</if>
</where>
</select>
二、多个参数传入
public List<Message> queryMessageList2(String command,String description);
<select id="queryMessageList2" resultMap="MessageResult">
select id,command,description,content from message where and command=#{command} and description=#{description}
</select>
由于是多个参数的传入,不能使用parameterType属性,传入基本数据类型String,也不能结合if标签取拼接sql
三、注解传入
public List<Message> queryMessageList3(@Param("command")String command,@Param("description")String description);
<s、elect id="queryMessageList3" parameterType="java.util.Map" resultMap="MessageResult">
select id,command,description,content from message
<where>
<if test="command != null and !"".equals(command.trim())">
and command=#{command}
</if>
<!-- like 查询一般会拼接concat()拼接两个字符串 -->
<if test="description != null and ''!=description.trim()">
and description like concat(concat('%',#{description}),'%')
</if>
</where>
</select>
注解传入的参数一般会放到map中所以 parameterType="java.util.map" ,可以使用if等其他标签判断取拼接sql
四、封装到map中
List<Integer> ids = newArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
ids.add(6);
ids.add(7);
ids.add(9);
Map<String, Object> params = newHashMap<String, Object>();
params.put("ids", ids);
params.put("command", "段子");
public List<Message> queryMessageList4(Map map);
<select id="queryMessageList" parameterType="java.util.Map" resultMap="MessageResult">
select * from message where title like concat(concat("%",#{command}),"%") and id in
<foreach collection="ids" index="index" item="item"open="(" separator="," close=")">
#{item}
</foreach>
</select>
五、放到list中
public List<Message> queryMessageList5(List list);
<select id="queryMessageList" parameterType="java.util.List"resultMap="MessageResult">
select * from message where id in(
<foreach collection="list" item="item" separator=",">
${item}
</foreach>
)
</select>
public List<Message> queryMessageList6(String[] commands);
<select id="queryMessageList" resultMap="MessageResult“>
select * from message where id in
<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>