mybatis如何封装List<String>类型属性
作者:hhtSeeTheWorld
这篇文章主要介绍了mybatis如何封装List<String>类型属性问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
数据库
有一个班级表
然后还有一个学生表
需要封装成的对象
/* *@author huanghaitao *@description *@Date 2022/1/27 */ @Data public class AClassAndStudent { private Integer classId; private String className; private List<String> stuNames; }
第一种写法
封装ResultMap写法
<resultMap id="AClassAndStudent" type="com.ruoyi.system.domain.AClassAndStudent"> <result column="class_id" property="classId"/> <result column="class_name" property="className"/> <collection property="stuNames" ofType="string"> <constructor> <arg column="stu_name"/> </constructor> </collection> </resultMap>
sql语句
<select id="testSelectSql" resultMap="AClassAndStudent"> select c.id class_id, c.name class_name, s.name stu_name from class c left join student s on c.id = s.class_id where c.id = 1 </select>
打印结果
AClassAndStudent(classId=1, className=3班, stuNames=[张三, 李四, 王二, 赵六])
第二种写法
<resultMap id="AClassAndStudent" type="com.ruoyi.system.domain.AClassAndStudent"> <result column="class_id" property="classId"/> <result column="class_name" property="className"/> <collection property="stuNames" column="class_id" ofType="string" select="selectStuName"/> </resultMap> <select id="testSelectSql" resultMap="AClassAndStudent"> select c.id class_id, c.name class_name from class c where c.id = 1 </select> <select id="selectStuName" resultType="java.lang.String"> select name stu_name from Student where class_id = 1 </select>
上面那个爆红 不用管的
sql语句打印 有点区别
但是结果是一样的
AClassAndStudent(classId=1, className=3班, stuNames=[张三, 李四, 王二, 赵六])
第三种写法
修改封装方式
新建一个学生类
/* *@author huanghaitao *@description *@Date 2022/1/27 */ @Data public class AStudent { private Integer id; private Integer classId; private String name; }
一个班级类,这个班级类包含学生类
import java.util.List; @Data public class AClassContainStudent { private Integer id; private String name; private List<AStudent> studentList; }
这样的话,ResultMap写法是下面这样的
<resultMap id="AClassContainStudent" type="com.ruoyi.system.domain.AClassContainStudent"> <id column="class_id" property="id"/> <result column="class_name" property="name"/> <collection property="studentList" resultMap="AStudent"/> </resultMap> <resultMap id="AStudent" type="com.ruoyi.system.domain.AStudent"> <id column="stu_id" property="id"/> <result column="class_id" property="classId"/> <result column="stu_name" property="name"/> </resultMap> <select id="testSelectSqlTwo" resultMap="AClassContainStudent"> select c.id class_id, c.name class_name, s.id stu_id, s.name stu_name from class c left join student s on c.id = s.class_id where c.id = 1 </select>
打印的结果
AClassContainStudent(id=1, name=3班, studentList=[AStudent(id=1,
classId=1, name=张三), AStudent(id=2, classId=1, name=李四),
AStudent(id=3, classId=1, name=王二), AStudent(id=4, classId=1,
name=赵六)])
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。