数据库字段名称和实体属性名称不同问题

发布时间 2023-04-01 19:46:09作者: 啥123

在使用Mapper代理开发时,出现数据库字段名称和实体属性名称不同问题,如数据库字段为brand_name,但是在定义实体类时,属性名称一般以驼峰形式命名,这样就会出现查询数据时,不能查出数据库该字段数据的情况。

解决方案一:对不一样的字段名起别名,别名与实体类属性名相同。

        <select id="selectAll" resultType="com.pojo.User">
            select id,brand_name as brandName,company_name as companyName,ordered,description,status from tb_brand;
        </select>

解决方案二:定义sql片段

    <sql id="user_column">
        id,brand_name as brandName,company_name as companyName,ordered,description,status
    </sql>

    <select id="selectAll" resultType="com.pojo.User">
        select <include refid="user_column"/> from tb_brand;
    </select>

解决方案三:resultMap,定义resultMap标签,在select标签中用resultMap标签替换resultType标签

    <resultMap id="userResultMap" type="com.pojo.User">
     <!--子标签有两个 id result
             id用于主键标签的映射
             result用于一般标签的映射-->
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>


    <select id="selectAll" resultMap="userResultMap">
        select * from tb_brand;
    </select>