mybatis(二)之if标签,forEach标签,where标签

mybatis(二)

resultMap标签

使用场景

  1. 数据库中查询字段为user_id,但是在JavaBean中mybatis赋值对象为userId,如果依旧是使用resultType的话,就会找不到,赋不上值
  2. column中写的是数据库中的字段名,property中写的是JavaBean中的字段名,resultMap中的id值与select标签中的resultMap值要一致,type返回值的类型
<mapper namespace="com.lxy.dao.ProductsDao">
    <resultMap id="findAllMap" type="com.lxy.bean.Products">
    <!--主键部分-->
        <id column="pid" property="id"/>
        <!--非主键部分-->
        <result column="pname" property="name"/>
        <result column="price" property="price"/>
        <result column="flag" property="flag"/>
    </resultMap>
  <select id="findAll" resultMap="findAllMap">
    SELECT p.pid,p.pname,p.price,p.flag,c.cid,c.cname
    from products p,category c
    where p.category_id = c.cid
  </select>
</mapper>

resultMap是在既不改变表,又不改变类的基础上,给变量赋值。

SQL动态标签

动态标签的介绍

  • (1)动态标签是什么?
    由于mybatis将sql与java代码分离(sql写在xml中)
    传统jdbc方法中,在写组合的多表复杂sql语句时,需要去拼接sql语句,稍不注意少写一个空格或“”,就会导致报错。
    这个Mybatis动态sql的功能,就拥有有效的解决了这个问题,Mybatis动态sql语言可以被用在任意的sql语句映射中。
    if标签,forEach标签,where标签
  • (2)动态标签有什么用?
    用来根据数据的不同来生成对应的sql
  • (3)应用场景
    高级搜索功能
    搜索有多个条件,不是每个条件输入框都有值 ,此时需根据值来生成where条件

if标签与where标签

例如,根据输入的内容来搜素
if标签中的test标签写条件,当有多个条件时,用and连接。

 <select id="findUserByCondition" parameterType="com.lxy.bean.User" resultType="com.lxy.bean.User">
        select  * from emp
        <where>
            <if test="ename!=null and ename != ''">
                and ename like #{ename}
            </if>
            <if test="job!=null and job!=''">
                and job = #{job}
            </if>
        </where>
    </select>

forEach标签和where标签

当要批量进行删除,查询等操作时,就可以使用forEach标签

<!--根据多个id来查找用户
      select * from user where id in(1,3,5)
      +++++++++
      select * from user where 1=1 and id in(1,3,5)

      collection:表示方法传入的集合对象的名字
      item:遍历集合时,会将集合中的元素赋值给item
      open表示你要拼接的sql以什么开始
      close:表示你拼接的sql以什么结束
      separator:表示拼接的分隔符

    -->
    <select id="queryUsersByIds" resultType="User">
        select * from user
        <where>
            <foreach collection="ids" item="id" open="and id in(" close=")"  separator=",">
                #{id}
            </foreach>
        </where>
    </select>
//根据多个ID来查找用户
//这里定义的变量,在UserDao中是不识别的,要想识别,必须在参数的前边加注解@Param("ids")
    List<User> queryUsersByIds(@Param("ids") List<Integer> ids);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值