(11) <resultMap>、<association>、<collection>标签

这篇博客详细介绍了MyBatis的resultMap标签的用法,包括如何在字段不一致时进行数据映射,以及一对一和一对多关联查询的配置。通过示例展示了如何将数据库查询结果映射到ResultEntity实体类,包括主键、普通字段的映射,以及User对象的一对一关联和User对象集合的一对多关联映射。这有助于提升数据库查询效率并简化数据转换过程。
摘要由CSDN通过智能技术生成

resultMap 标签

用法:当从数据库中查询的字段与要返回结果集字段不一致时候,将查询的数据映射为相应的结果集

  • id(resultMap) :标签的唯一标识
  • id(cloumn):数据库对应数据的唯一主键标识
  • result: 对应数据库中其他字段
  • jdbcType: 数据库字段对应的类型
  • property:所要映射的实体类对应的字段
<select id="QryResult" ResultMap="BaseResultMap">
    SELECT * FROM T_RESULT_USER
</select>
//从数据库中查询,返回结果为ResultEntity
<resultMap id="BaseResultMap" type="com.shop.entity.ResultEntity">
    <id column="ID" jdbcType="BIGINT" property="id" />
    <result column="COMMODIY_NAME" jdbcType="VARCHAR" property="Name" />
    <result column="COMMODIY_Price" jdbcType="BIGINT" property="Price" />
</resultMap> 
public class ResultEntity{
    private int id;
    private int Price;
    private string Name;
    <!---省略getter和setter方法---->
}

一对一关联查询

  • association:映射的pojo类中字段类型为其他类的时候用关联查询
//从数据库中查询,返回结果为ResultEntity
<resultMap id="BaseResultMap" type="com.shop.entity.ResultEntity">
    <id column="ID" jdbcType="BIGINT" property="id" />
    <result column="COMMODIY_NAME" jdbcType="VARCHAR" property="Name" />
    <result column="COMMODIY_Price" jdbcType="BIGINT" property="Price" />
    <association javaType="user" property="user">
        <id column="USER_ID" jdbcType="BIGINT" property="id" />
        <result column="USER_NAME" jdbcType="VARCHAR" property="UserName" />
        <result column="USER_ADRESS" jdbcType="VARCHAR" property="Adress" />
    </association>
</resultMap>
public class ResultEntity{
    private int id;
    private int Price;
    private string Name;
    private User user;              <!---多了这个---->
    <!---省略getter和setter方法---->
}
public class user{
    private int id;
    private string UserName;
    private string Adress;
     <!---省略getter和setter方法---->
}

一对多关联查询

collection: 映射的pojo类中字段类型为其他类集合的时候用关联查询

//从数据库中查询,返回结果为ResultEntity
<resultMap id="BaseResultMap" type="com.shop.entity.ResultEntity">
    <id column="ID" jdbcType="BIGINT" property="id" />
    <result column="COMMODIY_NAME" jdbcType="VARCHAR" property="Name" />
    <result column="COMMODIY_Price" jdbcType="BIGINT" property="Price" />
    <collection javaType="list" property="users" ofType="user">
        <id column="USER_ID" jdbcType="BIGINT" property="id" />
        <result column="USER_NAME" jdbcType="VARCHAR" property="UserName" />
        <result column="USER_ADRESS" jdbcType="VARCHAR" property="Adress" />
    </collection>
</resultMap>
public class ResultEntity{
    private string id;
    private string Name;
    private string Price;
    private List<user> Users;              <!---换成了这个---->
    <!---省略getter和setter方法---->
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值