一开始以为MyBatis增删改查能传入多个参数直接用参数名赋值即可,然后出了Bug找半天找不出来。
举个例子吧
//这个是用来更新最大成绩的函数
public interface ScoreDao {
@Update("update scores set top_score=#{score} where id=#{id}")
public int updateTopScore(int id,int score);
}
这个函数肯定是要多个参数,然后疯狂报错
org.apache.ibatis.exceptions.PersistenceException
Cause: org.apache.ibatis.binding.BindingException: Parameter ‘score’ not found.
解决办法:
直接用参数的位置
public interface ScoreDao {
@Update("update scores set top_score=#{0} where id=#{1}")
public int updateTopScore(int id,int score);
}
原因:因为传入多个参数时,mybatis会自动封装在map,key是索引
Map<Integer,Object> map=new HashMap();
所以还可以自己定义个Map作为参数
或者封装成对象
@Update("update scores set top_score=#{topScore} where id=#{id}")
public int updateTopScore(Score score);
我就直接封装成Score对象。
而且注意#{}里面的属性不是写属性名,而是写getter方法去掉get首字母小写。
比如
private Integer topScorehaha;
public Integer getTopScore() {
return topScorehaha;
}
#{topScore}而不是#{topScorehaha}
但我的推荐方法:
可以告诉mybatis别乱改 @param为参数指定名字
@Update("update scores set top_score=#{score} where id=#{id}")
public void updateTopScore(@Param("id")int id,@Param("score")int score) ;
总结:
参数可以为以下几种情况
1、单个参数:
基本类型:取值#{随便写},里面什么都可以,因为只有一个参数,mybatis直接对应上了。
2、多个参数:
取值:#{参数名}无效
可用:0、1
原因:因为传入多个参数时,mybatis会自动封装在map,key是索引
Map<Integer,Object> map=new HashMap();
3、可以告诉mybatis别乱改 @param为参数指定名字
4、用自己定义的类
5、Map
如果发现我的文章内容有错,欢迎给我指正,我只不过是一个刚学习ssm框架的初学者,感谢。