Mybatis开发总结

    xiaoxiao2021-04-12  37

    1、直接写语句,做组合查询也非常方便:

    [java]  view plain  copy  print ? SELECT * FROM hc_product           <where>               <if test="productname!=null">                   productName = '${productname}'               </if>               <if test="productid!=null">                   and p.productId = '${productid}'               </if>           </where>  

    这样就能完成多选择条件查询。

    2、一般的查询,直接返回实体类型即可。对于关联查询,处理方式之一就是:自己构造一个ResultMap,如名为Map1,将自己所需要的字段字段放在Map1中做映射。然后将查询的结果设置为Map1.

    在Map1中,我们可以多映射一些字段,为空的查询默认不映射。

    而在dao层接口中,我们一般会设置改方法的返回类型为:List<Map<String,Object>>,每一个list里面,存放的诸多map键值对,就对应查询上来的一条记录;而map键值对里面就是对应的字段名:字段值;

    3、Mybatis中mapper文件中的增删改方法,默认返回int类型。如果是增方法,则默认返回增加记录的条数,如果增加1条记录,则返回1,;如果增加100条记录,则返回100。改、删方法与增方法相同。

    4、Mybatis中不兼容不同的">"或者"<"符号,我们可以将sql语句写在"<!CDATA[你的sql]>"中,也可以使用对应的符号代替:

    < 小于 <     

    > 大于 >

    &  和 &

    '   单引号 '

    "   双引号"

    ps:写在 <!CDATA[你的sql]> 中的sql语句,mybatis不会对其中的内容再做智能解析。

    5、注意Mybatis中ResultMap和ResultType不一样。

    6、批量添加例子:

    [html]  view plain  copy  print ? <insert id="batchInsertRepay" parameterType="java.util.List">               <selectKey resultType="long" keyProperty="id" order="AFTER">                     SELECT  LAST_INSERT_ID()               </selectKey>                                      INSERT INTO hc_theory(id,Term,repayTime)                 VALUES              <foreach collection="list"  item="theory"  index="index"  separator=",">                 (                   #{theory.id},                   #{theory.term},                   #{theoryRepay.repaytime}               )             </foreach>         </insert>  

    7、返回数量(Integer)的处理:

    Mybatis映射中没有Java的基本类型int,返回Integer,有可能返回Null,所以要做如下处理:

    [java]  view plain  copy  print ? public Integer selectStockNumByProductId(String productId){           Integer i =stockMapper.selectStockNumByProductId(productId);                      return i==null?0:i;       }  
    转载请注明原文地址: https://ju.6miu.com/read-668144.html

    最新回复(0)