MyBatis 常见操作/错误

一、常用操作

  1. 批量操作

    批量操作:批量查询、批量插入、批量修改、批量删除,批量操作的效率要比for循环高很多。

    在Mybatis中批量操作最多就是批量插入和批量删除。一般采用foreach标签,但是这也与字段数量和条数有关,对于大批量的操作而言,推荐使用ExecutorType.BATCH插入方式。

    参照例如:http://www.pianshen.com/article/215691520/

 

二、常见错误

  1. 现象:MyBatis xml文件中查询的返回类型写成list或java.util.List时,执行sql时报 java.lang.UnsupportedOperationException错误。

   代码:

java:List<Long> findSignId();

xml:<select id="findSignId" resultType="java.util.List">
        select sign_id from group_manage
     </select>

   错误:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.UnsupportedOperationException

   解决方式:

xml:<select id="findSignId" resultType="long">
        select sign_id from group_manage
     </select>

   详解:返回类型应该是List里面的泛型,而不是List本身。

 

  2. 现象:MyBatis mapper类传递单个参数到xml中if判空,执行sql时报org.mybatis.spring.MyBatisSystemException异常。

   代码:

   错误:

   解决方式:

   详解:MyBatis 有自己的内置对象。

 

  3. 抽象业务代码

复制代码
复制代码
package com.xingyunliushui.dao;

import java.util.List;

public interface BaseQueryMapper {

    <T> List<T> selectAll(T record);

    <T> T selectOne(T record);

    <T> Integer countSelect(T record);
    
}
复制代码
复制代码

    调用时会报org.apache.ibatis.binding.BindingException异常,如:

复制代码
复制代码
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.nsac.xingyunliushui.user.RoleMapper.selectAll
    at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:225)
    at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:48)
    at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58)
    at com.sun.proxy.$Proxy225.selectAll(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
复制代码
复制代码

    解决办法:还是要写mapper对应的xml文件。

 

  3. 项目构建或编译报错:Can't map parameter "Serializable id" to "Long id"

   原因:@Mapper注解依赖引错了,应该是org.apache.ibatis.annotations.Mapper

 

posted @   如幻行云  阅读(430)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示