mybatis中常见的问题总结

以下全部举例基于springboot+mybatis项目中,SSH使用mybatis的写法也同样,只是形式不一样而已html

问题1.org.apache.ibatis.binding.BindingException: Parameter 'XXXX' not found.的问题解决办法java

  该问题的产生主要是mybatis中实例对象与xml文件之间映射关系上方法传参出现问题:spring

    1.当方法中不传参或者只传一个参数apache

      public interface UserMapper {数组

                        List<User> selectAllUser();springboot

                        int selectById(int id);mybatis

                        int insert(Student stu);
app

           }post

      那么xml文件中能够直接使用#{}方式获取参数,无需加@Param优化

      <insert id="insert" parameterType="com.ysq.model.student"><!--对应insert方法传过来的参数类型-->
        insert into inbox_template (name,age)
        values (#{name},#{age})<!--由于传过来的只有stu一个参数,所以咱们不须要使用对象.属性,直接使用属性便可-->
                     </insert>
    2.当方法中传入多个参数,则咱们须要给方法中的每一个参数加上@Param,不然在xml使用#{传入的参数名}会报错误(找不到参数名)

       User userLogin(@Param("username") String username, @Param("password") String password);

   
3.当方法中传人的既有参数又有对象时,对象也须要注解,通常参数的直接取,对象的须要对象.属性
      int selectBySelective(@Param("page")int page,@Param("stu")Student stu);

                    <select id="selectBySelective" resultMap="BaseResultMap">
                       select
                         <include refid="Base_Column_List" />
                      from student
                     where name = #{stu.name} and id = #{stu.id} limit 0 ,#{page}
                     </select>

     这种状况咱们能够优化:将参数和对象在封装成一个对象,而后再传人便可(相似分页时,咱们须要传入pageSize,User等)以下:

      <update id="update" parameterType="com.yoho.crm.dal.model.student"><!--此时obj则是对应page中的属性了-->
        update inbox_template
          set
           name = #{obj.name},
           age = #{obj.age}#这里obj为封装对象中的一个属性对象,若是咱们须要这个属性对象中的属性,则需对象.属性获取
           where id = #{obj.id}
           </update>

问题2:MyBatis 传List参数 nested exception is org.apache.ibatis.binding.BindingException: Parameter 'idList' not found.

转载:https://www.cnblogs.com/caoyajun33-blog/p/6875169.html

如下是相关代码:

Mapper.java--

mapper.xml

解决方案:

修改Mapper.java:

修改mapper.xml

 

 

缘由:

foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程当中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号做为分隔符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,可是在不一样状况下,该属性的值是不同的,主要有一下3种状况: 

    1. 若是传入的是单参数且参数类型是一个List的时候,collection属性值为list .
    2. 若是传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array .
    3. 若是传入的参数是多个的时候,咱们就须要把它们封装成一个Map了,固然单参数也能够封装成map,实际上若是你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,因此这个时候collection属性值就是传入的List或array对象在本身封装的map里面的key.
相关文章
相关标签/搜索