Java MyBatis实体类属性名与数据库字段表名称不一致解决办法

1585364631
2023-03-12 / 0 评论 / 377 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年03月12日,已超过1128天没有更新,若内容或图片失效,请留言反馈。

AI摘要

MyBatis解决实体类属性名与数据库字段名不一致问题有两种方法。一是查询时使用别名,如`select 数据库字段 as 实体属性`,可结合SQL片段复用。二是使用`resultMap`进行映射,通过``将数据库字段映射到实体类属性。`resultMap`是更灵活且推荐的方式,尤其适用于复杂映射场景。

MyBatis实体类属性名与数据库字段表名称不一致解决办法

1. 查询字段时使用别名

对不一样的列名起别名,让别名和实体类的属性名一样

<mapper namespace="org.example.mapper.UserMapper">
    <select id="selectAll" resultType="user">
        select 数据库表字段名 as 实体类属性名 from user;
    </select>
</mapper>

但是每次查询都需要重新定义一次别名

使用sql片段的方式解决

<mapper namespace="org.example.mapper.UserMapper">
    <sql id="dataName">
        数据库表字段名 as 实体类属性名
    </sql>
    <select id="selectAll" resultType="user">
        select <include refid="dataName" /> from user;
    </select>
</mapper>

但是此方法缺点不灵活

2.使用resultMap映射别名

<mapper namespace="org.example.mapper.UserMapper">
    <resultMap id="dataName" type="user">
        <id column="id" property="id"></id>
        <result column="数据库表字段名" property="实体类属性名"></result>
    </resultMap>

    <select id="selectAll" resultMap="dataName">
        select * from user;
    </select>
</mapper>

id作为主键映射,result作为一般字段映射

0

评论 (0)

取消