您的位置:首页 > 移动开发

Mybatis总结一——日期比较,参数传递,Mapper文件的编写

2018-12-04 17:35 2546 查看

  1 参数传递

        (1)如果不想把参数放在一个对象内封装,使用多个参数

           Dao接口层方法传参:

               Integer selectAnnualSales(@Param("tenantId")String tenantId,@Param("beginDate") String beginDate,@Param("endDate")String endDate,@Param("shopCode")String shopCode,@Param("type")Integer type);

           对应的Mapper.xml文件代码

  <select id="selectAnnualSales" resultType="java.lang.Integer">
        select sum(payment) from t_third_common_consumption
        <where>
            and date(create_time) BETWEEN date(#{beginDate}) and date(#{endDate})
            and shop_code=#{shopCode}
            and tenant_id=#{tenantId}
            <choose>
                <when test="type!=null">
                    and type = #{type} and payment >= 0
                </when>
                <otherwise>
                    and ( type = 0 or type = 1 )
                </otherwise>
            </choose>
        </where>
    </select>

        (1) 其中,注解@Param作用使得mapper中可以直接用#{参数名}取值,如果dao层方法没有该注解,则mapper层不能用#{参数名}取值,只能用0 ,1 等索引下标对应方法中传来的参数,如#{0}。

        (2)<where>元素会自动根据条件的语句数,删除无用的and。如本例会自动删除第一个and,之后的and会保留。

      (3)<choose> 

                   <when></when>

                  <otherwise></otherwise>

              </choose> 

              相当与if/else。

      (4)<select> 元素的属性 id 要和dao层方法名一致,且唯一。

2:日期使用

       数据库中的日期格式为:yyyy-MM-dd,字段类型为date

       后台传递的参数也应该符合该格式(非类型)

       例如:    Date  date=new Date();

                     SimpleDateFormat  format=new SimpleDateFormat ("yyyy-MM-dd");

                    String  sDate=format.format(date);      //将date转换为该格式的字符串

        在mapper文件的sql语句中,比较日期的大小,要将字符串转换为date(数据库字段对应的类型,格式)类型,用date()函数。

       例如 :select * from table1 where date(create_time)  between date(sDate) and date(endDate);

                   date()会将该字符串转换为该字符串格式的日期类型。注意如果传入的日期为:yyyy-MM-dd HH:mm:ss .使用date()后会自动变成 yyyy-MM-dd . 如 2019-02-01 23:32:32  会变成 2019-02-01 

                     

              

          

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: