Mybatis返回int类型为空时报错

当Mybatis查询结果为null时,返回int类型会抛出异常。解决方案是将返回类型改为Integer,避免返回null。在 Dao、Service 和 Service.Impl 层都需修改,同时可以使用MySQL的IFNULL函数转换NULL为0。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值