Mybatis中ORB映射

目录

1 MyBatis自动ORM失效

2 方案一:列的别名

3 方案二:结果映射(ResultMap - 查询结果的封装规则)

总结


 

1 MyBatis自动ORM失效

MyBatis只能自动维护库表”列名“与”属性名“相同时的一一对应关系,二者不同时,无法自动ORM。

2 方案一:列的别名

在SQL中使用 as 为查询字段添加列别名,以匹配属性名。

通过取别名,让列的别名和实体类属性名一致即可!

<mapper namespace="com.qf.mapper.ManagerMapper">
    <select id="findAll" resultType="Manager">
        select 
            mgr_id as id,
            mgr_name as name,
            mgr_pwd as password
        from t_managers
    </select>
</mapper>

 

3 方案二:结果映射(ResultMap - 查询结果的封装规则)

通过< resultMap id="" type="" >映射,匹配列名与属性名。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qf.mapper.ManagerMapper">
    <!--
        resultMap标签来完成结果映射的(手动实现映射)
        id是当前这个标签的标识
        type最终要映射(封装)那个对象的类型
    -->
    <resultMap id="findAllResultMap" type="com.qf.model.Manager">
        <!-- 手动指定哪个列封装到对象的哪个属性 -->
        <!-- id列封装使用id标签,其他列使用result标签 -->
        <!-- column是下方sql语句中的列名,property是封装的对象的属性名 -->
        <id column="mgr_id" property="id"/>
        <result column="mgr_name" property="name"/>
        <result column="mgr_pwd" property="password"/>
    </resultMap>
    <select id="findAll" resultMap="findAllResultMap">
        <!-- 因为列与封装的类的属性不一致,导致自动ORM失效 -->
        <!-- 需要手动映射,设置resultMap标签,在select标签中不再使用resultType
            而是使用resultMap且指定另外一个<resultMap>的id
         -->
        select * from t_managers
    </select>
</mapper>

总结

  • 当数据库的列和实体类属性不一致时,可以通过手动映射来完成

  • 手动关联映射,就不再使用resultType,而是使用resultMap,其中写resultMap标签的id

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值