【2023.11.26】Mybatis自定义映射规则学习

创建自定义映射规则

<select id="selectArtist" resultMap="test">
  select * from artist
</select>

在SQL语句标签中将resultType修改为resultMap,即自定义映射的id。

编写自定义映射规则:

<resultMap id="test" type="com.test.artist">
<result column="aID" property="aID_java"/>
</resultMap>

resultMap标签:id用以连接select标签,type代替了select标签中的resultType属性。

result标签:column代表数据库中的字段名,property代表赋值给的实体类成员变量名。


实现多表查询

1.一对多查询:

@Data
public class Teacher {
    int tid;
    String name;
    List<Student> studentList;
}
<select id="getTeacherByTid" resultMap="asTeacher">
select *, teacher.name as tname from student 
inner join teach on student.sid = teach.sid
inner join teacher on teach.tid = teacher.tid where teach.tid = #{tid}
</select>

<resultMap id="asTeacher" type="Teacher">
    <id column="tid" property="tid"/>
    <result column="tname" property="name"/>
    <collection property="studentList" ofType="Student">
        <id property="sid" column="sid"/>
        <result column="name" property="name"/>
        <result column="sex" property="sex"/>
    </collection>
</resultMap>

result.id:表示自定义映射的唯一标识,不能重复。

collection标签:property表示集合的成员变量名称,ofType表示集合数据泛型(为一个类)。

在collection标签中继续写子查询结果列表。

2.多对一查询:

<resultMap id="test2" type="Student">
    <id column="sid" property="sid"/>
    <result column="name" property="name"/>
    <result column="sex" property="sex"/>
    <association property="teacher" javaType="Teacher">
        <id column="tid" property="tid"/>
        <result column="tname" property="name"/>
    </association>
</resultMap>
<select id="selectStudent" resultMap="test2">
    select *, teacher.name as tname from student left join teach on student.sid = teach.sid
                                                 left join teacher on teach.tid = teacher.tid
</select>

association标签:property表示实体类的成员变量名称,ofType表示变量类型(为一个类)。

在association标签中继续写子查询结果列表。

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值