Mybatis返回int类型为空时报错 attempted to return null from a method with a primitive return type (int)
/**
* //查询上传文件是否存在
* @param fileMD5
* @param userID
* @param fileUrl
* @return
*/
@Select("SELECT userspaceid FROM r_userspace where userID=#{userID} and fileMD5=#{fileMD5} and fileUrl=#{fileUrl}")
Public int selectupFile(@Param("fileMD5")String fileMD5,@Param("userID")int userID,@Param("fileUrl")String fileUrl);
报错误原因
试图从具有原始返回类型(int)的方法返回null
严重: Servlet.service() for servlet [springMvc] in context with path [/myssm] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Mapper method 'com.slh.dao.IUserSpaceDAO.selectupFile attempted to return null from a method with a primitive return type (int).] with root cause
org.apache.ibatis.binding.BindingException: Mapper method 'com.slh.dao.IUserSpaceDAO.selectupFile attempted to return null from a method with a primitive return type (int).
解决方法
Mybatis的mapper文件的返回类型resultType为Integer:
返回类型设置为封装类型Integer而不是基本类型int。
1)sql查询时,没有该数据,返回的null,而不是0
2)int初始值为0,Integer是引用类初始值为null
Dao层
/**
* //查询上传文件是否存在
* @param fileMD5
* @param userID
* @param fileUrl
* @return
*/
@Select("SELECT userspaceid FROM r_userspace where userID=#{userID} and fileMD5=#{fileMD5} and fileUrl=#{fileUrl}")
Public Integer selectupFile(@Param("fileMD5")String fileMD5,@Param("userID")int userID,@Param("fileUrl")String fileUrl);
Service层
/**
* //查询上传文件是否存在
* @param fileMD5
* @param userID
* @param fileUrl
* @return
*/
public Integer selectupFile(String fileMD5,int userID,String fileUrl);
Service.Impl层
/**
* //查询上传文件是否存在
* @param fileMD5
* @param userID
* @param fileUrl
* @return
*/
@Override
public Integer selectupFile(String md5,int userID,String filePth) {
Integer id=userSpaceDao.selectupFile(md5,userID,filePth);
if(id==null){
id=0;
}
return id;
}
另外:若遇到该问题,可使用MySQL的IFNULL函数和MAX函数,将返回的NULL值转换为0。例如,可将上述SQL语句改为:
SELECT IFFULL(MAX(name),0) AS name FROM user WHERE id = #{id}
select (case sex when 'null' then 0 end ) from salary;
int和integer的区别
1、Ingeter是int的包装类,int的初值为0,Ingeter的初值为null;
2、Integer是对象,用一个引用指向这个对象,而int是基本类型,直接存储数值。
java中的数据类型分为基本数据类型和引用类类型,int是基本数据类型,integer是引用类类型,引用类类型也就是一个类,所以初始化为null。