MyBatis-Plus通过注解的方式绑定一对多查询

有一个查询活动的方法需要把所属组织放到实体里面,通过绑定自定义resultMap实现一对多查询

实现思路

首先创建一个对应的Mapper然后在Mapper中自定义resultMap和查询方法,然后通过mybatis中的TableName注解的resultMap绑定

在application.yml中配置Mapper扫描路径

mybatis-plus:
  mapper-locations: classpath*:static/mapper/*Mapper.xml

自定义ActivitiesMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.school.demo.mapper.auto.ActivitiesMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="ActivitiesResultMap" type="com.school.demo.model.auto.Activities">
        <id column="id" property="id" />
        <result column="origanization_id" property="origanizationId" />
        <result column="up_time" property="upTime" />
        <result column="view_num" property="viewNum" />
        <result column="content" property="content" />
        <result column="label" property="label" />
        <result column="title" property="title" />
        <result column="status" property="status" />
        <result column="is_set_join_num" property="isSetJoinNum" />
        <result column="imgs" property="imgs" />
        <result column="column_11" property="column11" />
        <result column="column_12" property="column12" />
        <association property="organization" column="origanization_id" select="findOrganization" />
        <association property="peopleNumManagement" column="id" select="findDate" />
    </resultMap>

    <select id="findOrganization" resultType="com.school.demo.model.auto.Organization">
        SELECT * FROM organization WHERE id = #{origanizationId}
    </select>

    <select id="findDate" resultType="com.school.demo.model.auto.PeopleNumManagement">
        SELECT * FROM people_num_management WHERE a_id = #{id}
    </select>


</mapper>

配置实体类

import com.baomidou.mybatisplus.annotation.TableName;

@TableName(resultMap = "ActivitiesResultMap")
public class Activities extends Model {

之后继续使用mybatis-plus的各种方法可以正常使用,例如分页之类

posted @ 2021-04-25 09:42  两小无猜  阅读(1583)  评论(2编辑  收藏  举报