Mybatis框架调用有返回值的存储过程的参数必须为Map或者自定义实体类,以下分别为两者的使用案例(无论是Springboot框架还是SpringMVC都可使用此案例【这句话仅针对小白】):
附加:以下接收返回值的参数名 result 可自定义,如:yourParamName,类型也可根据返回类型自定义,如:String。如果使用实体类的方法调存储过程,则实体类中用于接收返回值的属性是必须要添加的;如果使用Map的方法调存储过程,则用于接收返回值的key可添加也可不添加,因为mybatis会自动将用于接收返回值的参数名及返回值添加到Map中。如果出现这种报错信息,检查自己调用的存储过程名字是否写错
方法一:
使用Map作为参数调用有返回值的存储过程
//以下为Java接口实现代码
@Transactional
public Map<String, Object> removeOrderItems(Integer kpoiId) {
Map<String, Object> map = new HashMap<>();
Map<String,Integer> param = new HashMap<>();//由于mybatis调有返回值的存储过程参数必须为map或者某一个类,因此此处使用map
param.put("kpoiId",kpoiId);//参数
//key名 result可以事先put到map中,传个默认值,也可以不设置,mybatis会自动将接收返回值的参数名以及值put到Map中
kitchenPurchaseOrderItemsMapper.deletePurchaseOrder(param);//会将返回值放入到参数map中,key名为result
map.put("code",param.get("result"));
return map;
}
//以下为Java Mapper接口声明方法
@Mapper
public interface KitchenPurchaseOrderItemsMapper {
void deletePurchaseOrder(Map param);
}
<!--以下为Mybatis Mapper.xml具体调用的代码-->
<select id="deletePurchaseOrder" statementType="CALLABLE">
{call purchase_remove_order(
#{kpoiId,mode=IN,jdbcType=INTEGER},
#{result,mode=OUT,jdbcType=INTEGER}
)}
</select>
<!--注意:接收返回值的参数一定要加上 mode=OUT 如:#{result,mode=OUT,jdbcType=INTEGER}-->
方法二:
使用自定义实体类作为参数调用有返回值的存储过程
查看 KitchenPurchaseSupplier实体类 详情
//以下为Java接口实现代码
/**
*@Transactional事务注解一般用在需要修改数据库次数大于1的情况,(rollbackFor = Exception.class)这个部分是当具体实现时进行了try{}catch(Exception e){}的情况才需要加,否则不用加
*Exception.class是根据catch捕获的异常而定,一般没有特殊需求为了代码的简洁易懂和方便下次的复制粘贴,直接用Exception 即可
*/
@Transactional(rollbackFor = Exception.class)
public Map<String, Object> savePurchaseSupplier(String info) {//info是由前端传过来的json字符串信息
Map<String, Object> map = new HashMap<>();
if(info != null){
try {
KitchenPurchaseSupplier supplier =GsonUtil.parseJsonWithGson(info,KitchenPurchaseSupplier.class);//通过Gson将json字符串转换为实体类对象,此类可根据自己实际业务需求自行定义
purchaseSupplierMapper.insertPurchaseSupplier(supplier);//调用有返回值的存储过程
map.put("code",supplier.getResult());//拿到存储过程返回的处理结果
} catch (Exception e) {
e.printStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//当方法上有@Transactional注解时,代码进行了异常捕获后需要手动进行事务回滚,如果没有catch异常则不需要写这句话
map.put("code",0);
}
}else{
map.put("code",0);
}
return map;
}
//以下为Java Mapper接口声明方法
@Mapper
public interface PurchaseSupplierMapper {
void insertPurchaseSupplier(KitchenPurchaseSupplier info);
}
<!--以下为Mybatis Mapper.xml具体调用的代码-->
<select id="insertPurchaseSupplier" statementType="CALLABLE">
{call purchase_save_supplier(
#{goodsId,jdbcType=INTEGER},
#{wsId,jdbcType=INTEGER},
#{wsName,jdbcType=VARCHAR},
#{wsRemark,jdbcType=VARCHAR},
#{price,jdbcType=REAL},
#{expireDate,jdbcType=DATE},
#{result,mode=OUT,jdbcType=INTEGER}
)
}
</select>
<!--注意:接收返回值的参数一定要加上 mode=OUT 如:#{result,mode=OUT,jdbcType=INTEGER}-->
KitchenPurchaseSupplier 实体类
报错信息