Spring图书服务查询接口报500错误:Author对象为空问题排查
问题根源
你遇到的空指针错误,核心原因是数据库中存在未关联作者的图书记录(即Book实体的author字段为null),但在DTO转换时没有处理这种null场景,直接调用了null对象的方法。
代码问题分析
AuthorMapper的null判断缺失:
authorToAuthorDto方法直接接收Author对象并调用author.getId()、author.getName(),完全没判断入参是否为null。当book的author是null时,传入这个方法就会触发空指针异常。public AuthorDto authorToAuthorDto(Author author) { AuthorDto authorDto = new AuthorDto(); authorDto.setId(author.getId()); // author为null时此处报错 authorDto.setName(author.getName()); return authorDto; }BookMapper未提前拦截null的author:
bookToBookDto方法中,直接将book.getAuthor()传给AuthorMapper转换,没有先判断这个author是否为null,导致null对象流入转换方法。
修复方案
方案1:给AuthorMapper添加null判断
在转换前先检查入参是否为null,避免调用null对象的方法:
public AuthorDto authorToAuthorDto(Author author) { if (Objects.isNull(author)) { return null; // 或者返回空的AuthorDto实例,根据业务需求选择 } AuthorDto authorDto = new AuthorDto(); authorDto.setId(author.getId()); authorDto.setName(author.getName()); return authorDto; }
方案2:在BookMapper中提前处理null的author
在调用AuthorMapper转换前,先判断book的author是否存在:
public BookDTO bookToBookDto(Book book) { if (Objects.isNull(book)) { return null; } BookDTO bookDTO = new BookDTO(); bookDTO.setId(book.getId()); bookDTO.setName(book.getName()); // 先判断author是否不为null,再进行转换 if (Objects.nonNull(book.getAuthor())) { bookDTO.setAuthorDto(authorMapper.authorToAuthorDto(book.getAuthor())); } else { bookDTO.setAuthorDto(null); // 或设置默认值,比如new AuthorDto() } return bookDTO; }
额外建议
如果业务要求图书必须关联作者,可以在数据库层面给book表的author_id字段添加非空约束,从根源避免出现无作者的图书记录;如果允许无作者的图书,就必须在代码中统一处理这种null场景。
内容的提问来源于stack exchange,提问作者Ulan Duishenaliev
相关产品推荐
相关产品推荐

