在 Java + MyBatis 项目中,空指针异常(NullPointerException,NPE) 是非常常见的问题。下面按最常见原因 → 示例 → 解决方式给你系统梳理一下。
new 创建 MapperUserMapper userMapper = new UserMapper(); // ❌
userMapper.selectById(1); // NPE
@Autowired
private UserMapper userMapper;
@MapperScan("com.xxx.mapper")@MapperresultType / resultMap 不匹配User user = userMapper.selectById(999);
user.getName(); // ❌ NPE
if (user != null) {
user.getName();
}
或数据库保证存在:
SELECT ... WHERE id = #{id}
nulluserMapper.selectByName(null);
WHERE name = #{name}
一般不会 NPE,但:
WHERE name = #{user.name} <!-- user 为 null 时 NPE -->
<if test="user != null">
AND name = #{user.name}
</if>
public class User {
private Integer userId;
}
数据库字段:user_id
mybatis:
configuration:
map-underscore-to-camel-case: true
或:
<result column="user_id" property="userId"/>
<if test="status.equals('1')"> <!-- status 为 null → NPE -->
<if test="status != null and status.equals('1')">
或:
<if test="'1'.equals(status)">
private User user;
public void test() {
user.getName(); // ❌
}
User select(@Param("id") Integer id);
WHERE id = #{userId} <!-- 名称不一致 -->
Map<String, Object> map = userMapper.select();
map.get("age").toString(); // age 不存在 → NPE
@Autowirednew Mapper如果你愿意,可以把报错堆栈 / Mapper 代码 / XML贴出来,我可以直接帮你定位是哪一行导致的 NPE。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。