MyBatis SQL应用

1.数据库使用xml文件中防止SQL注入,涉及模糊查询的语句

 <if test="objectName!=null and objectName!=''">
      AND OBJECT_NAME like concat(concat('%',#{objectName}),'%')
 </if>

2.

map和List,array相比,map是用K,V存储的,在foreach中,使用map时,index属性值为map中的Key的值。

因为map中的Key不同于list,array中的索引,所以会有更丰富的用法。

批量插入

<insert id="ins_string_string">
        insert into string_string (key, value) values
        <foreach item="item" index="key" collection="map"
            open="" separator="," close="">(#{key}, #{item})</foreach>
</insert>


3.select的例子

<select id="sel_key_cols" resultType="int">
        select count(*) from key_cols where
        <foreach item="item" index="key" collection="map"
            open="" separator="AND" close="">${key} = #{item}</foreach>
</select>

可以看到这里用key=value来作为查询条件,对于动态的查询,这种处理方式可以借鉴。 一定要注意到$和#的区别 ,$的参数直接输出,#的参数会被替换为?,然后传入参数值执行。

DEBUG [main] - ==>  Preparing: select count(*) from key_cols where col_a = ? AND col_b = ? 
DEBUG [main] - ==> Parameters: 22(Integer), 222(Integer)
DEBUG [main] - <==      Total: 1

4.foreach 循环LIST

  • item:循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。 具体说明:在list和数组中是其中的对象,在map中是value。 该参数为必选。

<select id="countByUserList" resultType="_int" parameterType="list">
select count(*) from users
  <where>
    id in
    <foreach item="item" collection="list" separator="," open="(" close=")" index="">
      #{item.id, jdbcType=NUMERIC}
    </foreach>
  </where>
</select>

注:select count(*) from users WHERE id in ( ? , ? ) 


5.foreach 循环数组

JAVA传入参数

public void testQuery() {
    ColInfoDao dao=(ColInfoDao)ctx.getBean("colInfoDao");
    Map map = new HashMap();
    map.put("userId", "tom");
    map.put("password", "123");
    String[] a = { "20000001", "20000002" };
    map.put("classIds", Arrays.asList(a));
    Object password = dao.query(map);
    System.out.println("password:" + password);
    Assert.assertEquals("123", password);
}

XML文件使用

<select id="queryPasswordByUserId" parameterClass="java.util.Map"      resultClass="java.lang.String">
        <![CDATA[
        select PASSWORD as password from T_S_P_USER
        ]]>
        <dynamic prepend="where">
            <isNotEmpty prepend="AND" property="userId">
                USER_ID=#userId#
            </isNotEmpty>
            <isNotEmpty prepend="AND" property="password">
                PASSWORD=#password#
            </isNotEmpty>
            <isNotEmpty prepend="AND" property="classIds">
                <iterate property="classIds" open="(" conjunction="OR" close=")">
                    CLASS_ID = #classIds[]#
                </iterate>
            </isNotEmpty>
        </dynamic>
</select>




猜你喜欢

转载自blog.csdn.net/yangliuhbhd/article/details/71271184