解决mybatis一对多查询resultMap只返回了一条记录问题

问题描述:因为领导的一个需求,需要用到使用resultMap,很久没使用了,结果就除了点意外。就记录下这个问题
准备两个类:author(作者)和book(书),数据库创建对应的author->book一对多的数据

@Datapublic class Author {private Integer id; private String name; private String phone; private String address; private List books; }@Datapublic class Book {private Integer id; private String name; private String press; private BigDecimal price; private Integer authorId; }

开始的Mapper.xml文件
select t1.*,t2.* fromauthor t1 inner join book t2 on t1.id=t2.author_idwhere t1.id=#{id}

使用postman执行查看结果:
{"code": "200","msg": "成功","data": {"id": 1,"name": "法外狂徒张三","phone": null,"address": null,"books": [{"id": 1,"name": "法外狂徒张三","press": "人民出版社","price": 10.00,"authorId": 1}]}}

发现问题:本来author对应book有两条记录,结果books里面只返回了一条记录。
问题原因:2张表的主键都叫id,所以导致结果不能正确展示。
解决方法:1、主键使用不用的字段名。2、查询sql时使用别名
1、主键使用不用的字段名,涉及到更改数据库,只需要更改其中一个即可 。这里演示将book的id更改为book_id
select t1.*,t2.* fromauthor t1 inner join book t2 on t1.id=t2.author_idwhere t1.id=#{id}

2、查询sql时使用别名。这里演示将查询book时id 更改别名为 bookId
select t1.*,t2.id as bookId, t2.* fromauthor t1 inner join book t2 on t1.id=t2.author_idwhere t1.id=#{id}

【解决mybatis一对多查询resultMap只返回了一条记录问题】到此这篇关于mybatis一对多查询resultMap只返回了一条记录的文章就介绍到这了,更多相关mybatis一对多查询resultMap内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读