MyBatis自动封装问题


问题描述

在数据库建表时,更习惯于使用下滑线连接不同单词,如某字段名称user_name,而在写代码时,却习惯于使用驼峰命名法定义变量,用Java举例,某个实体类的属性String userName;

当使用MyBatis时,定义SQL语句 :

<mapper namespace="com.mapper.UserMapper">
    <select id="selectAll" resultType="com.pojo.User">
        SELECT * FROM user
    </select>
</mapper>

当程序执行后,MyBatis自动封装结果为null;

解决办法

  1. 起别名:在定义SQL语句时,使用as给字段起别名,如上面举例的SQL语句可更改为:

    <mapper namespace="com.mapper.UserMapper">
        <select id="selectAll" resultType="com.pojo.User">
            SELECE user_name as userName FROM user
        </select>
    </mapper>
    

    这样做的缺点显而易见:当字段数量较多以及SQL语句较多时,这样做非常麻烦。

    为了解决此问题,可以定义SQL片段,以上例子使用SQL片段后修改为:

    <mapper namespace="com.mapper.UserMapper">
        <sql id="user_column">
            user_name as userName
        </sql>
        <select id="selectAll" resultType="com.pojo.User">
            select
                <include refid="user_column" />
            from tb_brand
        </select>
    </mapper>
    

    这样做同样有缺点:当查询字段不同时,要定义新的SQL片段,依然麻烦。

  2. resultMap:使用resultMap将数据库字段名映射到实体类属性名,如:

    <mapper namespace="com.mapper.UserMapper">
        <resultMap id="userResultMap" type="com.pojo.User">
            <result column="user_name" property="userName" />
        </resultMap>
        
        <select id="selectAll" resultMap="userResultMap">
            select * from tb_brand
        </select>
    </mapper>
    

    这样做也存在一定局限性,同时需要特别注意:select标签中的resultType属性要修改为resultMap,属性值为resultMap标签的id。

  3. 修改配置文件:在mybatis-config.xml配置文件中加入以下内容:

    <configuration>
        <settings>
            <setting name="mapUnderscoreToCamelCase" value="true"/>
        </settings>
    </configuration>
    

    修改过后,MyBatis会将查询到的结果自动转换成驼峰命名。

以上便是解决MyBatis查询字段含下划线不能自动封装问题的全部内容,如有问题或者更好的解决办法,欢迎留言讨论。


文章作者: Cikian
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Cikian !
评论
  目录