mybatis 连表查询mapper格式

mybatis 连表查询mapper格式

实体类

public class StudentEntity {
private int id;
private String name;
private TeacherEntity teacherEntity;  //属性是关联表实体类
 //构造(有参,无参),set ,get ,toSting
}


public class TeacherEntity {
    private int id;
    private String name;
    //构造(有参,无参),set ,get ,toSting
 }

方法一直接查询映射

格式

<select id="接口名" resultMap="自定义整合后的map名称,如下">
    select * from student;
</select>

<resultMap id="自定义整合后的map名称" type="A表实体类">
    <association property="A表实体类需要赋值的字段属性名" column="A表内需要在B表查询的值" javaType="B表实体类" 	select="B表查询语句ID" />
</resultMap>

<select id="查询语句ID" resultType="B表实体类">
    select * from teacher where id = #{id}
</select>

###示例

<select id="getStudents" resultMap="StudentTeacher">
    select * from student;
</select>

<resultMap id="StudentTeacher" type="com.example.webdemo.entity.StudentEntity">
    <association property="teacherEntity" column="tid" javaType="com.example.webdemo.entity.TeacherEntity" select="getTeacher" />
</resultMap>

<select id="getTeacher" resultType="com.example.webdemo.entity.TeacherEntity">
    select * from teacher where id = #{id}
</select>

方法二 通过查询结果后映射关系

格式

 <select id="接口名" resultMap="自定义映射map如下">
       select a.id as aid,b.id as bid,a.name as studentname,b.name as teachename from student a left join  teacher b on 				a.tid = b.id;
</select>

<resultMap id="自定义映射map" type="需要返回的主表实体类">
    <id property="实体类字段id" column="如上查询结果id" />
    <result property="实体类字段" column="如上查询结果中的字段" />
    <association property="实体类字段" javaType="关联表的实体类">
        <result property="关联表的实体类字段" column="如上查询结果中的字段"/>
    </association>
</resultMap>

###示例

<select id="getStudents2" resultMap="studentTeache2">
    select a.id as aid,b.id as bid,a.name as studentname,b.name as teachename from student a left join  teacher b on a.tid = b.id;
</select>

<resultMap id="studentTeache2" type="com.example.webdemo.entity.StudentEntity">
    <id property="id" column="aid" />
    <result property="name" column="studentname" />
    <association property="teacherEntity" javaType="com.example.webdemo.entity.TeacherEntity">
        <result property="name" column="teachename"/>
    </association>
</resultMap>

所有的实体类引用最好使用全路径如:com.example.webdemo.entity.TeacherEntity

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值