当方法的返回类型是数组或集合时,不要返回null,尽量返回容量为0的数组或集合

    今天测试3.0的后台代码时,遇到了一个空指针的bug,是由于调用的方法返回的是集合,由于实际返回的是null,后头有调用了这个对象的方法,导致空指针。这段代码的质量需要改善,如果返回容量为0的集合,则完全可以避免空指针。先贴错误代码。

  1. public Result queryStoreServiceAttendList(AttendParamVo vo) {         
  2.     Result result = new Result();  
  3.     try {  
  4.         List<AnalysisDetailBean>  details = attendanceManager.queryStoreServiceAttendList(vo);  
  5.         List<ServerPopBean> allService = storeService.queryServerListByStoreAndYn(vo.getStoreId());  
  6.         Map<String, ServiceAttendAnalysisVo> attentVoMap = new HashMap<String, ServiceAttendAnalysisVo(allService.size());//null pointer!  
  7.         int totalDays= DateUtils.getIntervalDays(vo.getStartDate(), vo.getEndDate());  
  8.         .....  
  9. }  
  1. @Override  
  2. public List<ServerPopBean> queryServerListByStoreAndYn(int storeId) {   
  3.     try {  
  4.         if(storeId != 0){  
  5.             return serverPopManager.queryServerListByStoreAndYn(storeId);  
  6.         }else{  
  7.             return null;  
  8.         }  
  9.     } catch (Exception e) {   
  10.         log.error("Query server list by store and yn error!", e);  
  11.         return null;  
  12.     }  
  13. }  
    可以看出来,如果要调用queryServerListByStoreAndYn()方法的返回对象,一个必要的操作是判空!但是,调用的代码并没有进行判空,直接操作,造成了空指针一样。
    怎样让调用者省心不用判空?So easy!返回容量为零的集合。这样,既保持了代码的逻辑不变,而且调用方便不用判空。
    修改后的代码如下:

  1. @Override  
  2. public List<ServerPopBean> queryServerListByStoreAndYn(int storeId) {   
  3.     try {  
  4.         if(storeId != 0){  
  5.             return serverPopManager.queryServerListByStoreAndYn(storeId);  
  6.         }else{  
  7.             return new ArrayList<ServerPopBean>();  
  8.         }  
  9.     } catch (Exception e) {   
  10.         log.error("Query server list by store and yn error!", e);  
  11.         return new ArrayList<ServerPopBean>();  
  12.     }  
  13. }  
    如此一来,便可完全规避不必要的空指针异常。《effective java》一书有对这种代码的详解。
    对ibatis框架的getList();方法做了简单的测试,发现这个方法在查询无结果的情况下,返回的是一个空的ArrayList,框架的设计还是很合理地 。
<think> 我们正在讨论MyBatis中当返回类型数组,mapper文件中resultType应该如何设置。根据之前的引用和问题,我们可以总结如下: 根据引用[3]:在SpringBoot应用中,如果想返回一个表的主键id构成的Long型数组Long[],在XxxMapper.xml文件中这样定义: <select id="selectIds" parameterType="int" resultType="Long"> select id from sys_job_log limit #{count} </select> 注意:这里返回的是多个id,即一个列表(数组),但resultType设置为数组中元素的类型(这里是Long),而数组类型本身。 为什么可以这样?因为MyBatis对于返回集合(包括数组)的处理是:我们只需要指定集合中元素的类型,而需要指定集合类型(如List、数组等)。MyBatis会自动将查询结果封装成集合。 具体来说: - 如果方法返回单个对象,则resultType设置为该对象的类型(别名)。 - 如果方法返回多个对象(即集合数组),则resultType仍然设置为集合中元素的类型。 因此,当返回数组,resultType应该设置为数组元素的类型,而数组类型。 例如: - 返回Long数组:resultType="Long" - 返回自定义对象数组:resultType="com.example.User" 另外,引用[1]和[2]也提到了resultType的使用规则,包括基本数据类型和自定义对象类型。 然而,需要注意的是,在MyBatis中,数组集合(List)的处理方式是一样的,都是使用元素类型作为resultType。 示例代码: Mapper接口: public interface UserMapper { Long[] selectUserIds(int count); } Mapper.xml文件: <select id="selectUserIds" resultType="Long"> select id from user limit #{count} </select> 这里,虽然接口方法返回的是Long数组,但xml中的resultType写的是"Long"(即元素类型)。 如果返回的是自定义对象数组,比如User对象数组: public interface UserMapper { User[] selectUsers(); } 那么Mapper.xml应该是: <select id="selectUsers" resultType="com.example.User"> select * from user </select> 总结:无论返回的是List还是数组,在resultType属性中,我们都只需要写元素的类型(全限定名别名)。 但是,有一个特殊情况:如果返回的是基本类型的数组(如int[]),那么resultType应该写基本类型的包装类别名。因为MyBatis使用包装类来处理基本类型。 例如:返回int[],那么resultType应该写为"int"(别名)"java.lang.Integer"。 注意:MyBatis内置了一些基本类型的别名,如: int -> _int Integer -> int String -> string Long -> long ... 所以,对于基本类型数组,我们通常使用其包装类的别名,例如: int[] -> resultType="int" (这里int是Integer的别名) long[] -> resultType="long" (long是Long的别名) 但是,实际中更推荐使用包装类,因为基本类型数组可能会遇到null值问题。 因此,回答用户问题:当返回类型数组,resultType应设置为数组元素的类型(全限定类名别名),而数组类型本身。 最后,我们可以生成一些相关问题,以帮助用户扩展理解。 </think> 在 MyBatis 中,当查询返回数组类型,`resultType` 的设置遵循特定规则。根据引用信息和最佳实践: ### 🔍 数组返回类型的 `resultType` 设置规则 1. **返回基本类型数组** 直接使用基本类型的包装类名称(全限定名别名)作为 `resultType` ```xml <!-- 返回 Long 型数组 --> <select id="selectIds" resultType="Long"> SELECT id FROM sys_job_log LIMIT #{count} </select> ``` *示例:返回 `Long[]` 类型数组[^3]* 2. **返回对象数组** 使用对象的全限定类名(已配置的别名)作为 `resultType` ```xml <!-- 返回 User 对象数组 --> <select id="selectUsers" resultType="com.example.User"> SELECT * FROM users </select> ``` 3. **返回基本类型数组的特殊情况** 对于 `int[]` 等基本类型数组,使用对应的包装类型别名: ```xml <!-- 返回 int[] 数组 --> <select id="getIntArray" resultType="_int"> SELECT num FROM numbers </select> ``` ### ️ 关键注意事项 1. **MyBatis 自动处理集合类型** 需要显式声明数组类型(如 `Long[]`),MyBatis 会根据方法签名自动封装结果: ```java // Mapper 接口方法 Long[] selectIds(int count); // MyBatis 自动将多条记录封装为 Long[] ``` 2. **集合类型统一处理** 数组集合(List/Set)使用相同的 `resultType` 配置规则: ```xml <!-- 返回 List<Long> Long[] 使用相同配置 --> <select id="getIds" resultType="Long">...</select> ``` 3. **避免常见错误** - ❌ 错误写法:`resultType="Long[]"` - ✅ 正确写法:`resultType="Long"` ### 📝 完整示例 ```xml <!-- 返回 Long[] 数组 --> <select id="getUserIds" resultType="Long"> SELECT id FROM users WHERE status = 1 </select> <!-- 返回自定义对象数组 User[] --> <select id="getActiveUsers" resultType="com.example.User"> SELECT * FROM users WHERE active = true </select> ``` *通过指定元素类型而非容器类型实现数组返回[^2][^3]* --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值