Mybatis之解决collection一对多问题(显示的结果没有整合到一起)
作者:肖家庄小王
这篇文章主要介绍了Mybatis之解决collection一对多问题(显示的结果没有整合到一起),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
先简单说一下我遇到的问题
我是两张表关联查询(其实是主表都全部数据,但是只保存其他表的ID),主表保存有附表的数据,但是需要将附表的数据整合到主表相同的目录下,方便前台调用。
需要的结果样式如下图1所示,但是获取到的结果总是分开的,resultMap和collection节点内容都对了好几遍,写的没问题,但是出现结果如图二所示:然后最总发现是主表的主键ID所导致的,因为主表ID每条都不一样,虽然在SQL中没查,但是编译器好像也会获取,按主键区分,所以不能直接使用原有的主键内容,组要手动设置一个,这个设置的内容是你需要划分的依据字段,如我是根据DIAGNOSIS_NO这个字段来划分数据哪些是一组的,所以用这个字段来代替主键id。
图一
{ "code": 200, "msg": "成功获取", "data": [ { "id": "", "nursingplanDtoList": [ { "id": "", "DIAGNOSIS_NO": "38.0", "FACTOR_NO": 24, "DIAGNOSIS_FACTOR": "疼痛不适。" }, { "id": "", "DIAGNOSIS_NO": "38.0", "FACTOR_NO": 25, "DIAGNOSIS_FACTOR": "活动无耐力。" }, ], "PATIENT_ID": "20005369", "VISIT_ID": "1", "ADMISSION_DATE": "2020-09-22 10:20", } ] }
图二
{ "code": 200, "msg": "成功获取", "data": [ { "id": "", "nursingplanDtoList": [ { "id": "", "DIAGNOSIS_NO": "38.0", "FACTOR_NO": 24, "DIAGNOSIS_FACTOR": "疼痛不适。" } ], "PATIENT_ID": "20005369", "VISIT_ID": "1", "ADMISSION_DATE": "2020-09-22 10:20", }, { "id": "", "nursingplanDtoList": [ { "id": "", "DIAGNOSIS_NO": "38.0", "FACTOR_NO": 25, "DIAGNOSIS_FACTOR": "活动无耐力。" } ], "PATIENT_ID": "20005369", "VISIT_ID": "1", "ADMISSION_DATE": "2020-09-22 10:20", }, ] }
首先先看一下我的两张表
表一:factorDict
表二:nursingDiagnosis
Sql查询语句
SELECT n.DIAGNOSIS_NO as id, n.PATIENT_ID, n.VISIT_ID, n.ADMISSION_DATE, n.DIAGNOSIS_NO, n.DIAGNOSIS_STATUS, n.DIAGNOSIS_SORT, n.EXPECTED_TARGET, n.START_DATE, n.STOP_DATE, n.FACTOR_ID as FACTOR_NO, n.FACTOR_STATUS, f.DIAGNOSIS_FACTOR FROM nursingDiagnosis n LEFT JOIN factorDcit f on n.FACTOR_ID=f.id WHERE n.PATIENT_ID = #{Patient_id} AND n.VISIT_ID = #{Visit_id} AND n.ADMISSION_DATE=#{Admission_Date} AND n.DIAGNOSIS_NO='38.0' ORDER BY n.DIAGNOSIS_STATUS DESC, n.DIAGNOSIS_SORT
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。