Mybatis处理字段名和属性名不一致的几种方法

Mybatis处理字段名和属性名不一致的几种方法

    1.为查询的字段设置别名,和属性名保持一致
    2.当字段符合MySQL的要求使用,而属性符合Java的要求使用驼峰
      -此时可以在mybatis核心配置文件中设置全局配置来自动将下划线映为驼峰
    3.使用resultMap自定义映射

这里以实现员工信息接口中的方法来体现,下面是具体的代码实现:
接口中的方法为:

    //根据id来查询员工信息
    Emp getEmpByEmpId(@Param("empId") Integer empId);

第一种方式:设置别名

    <select id="getEmpByEmpIdOld" resultType="Emp">
        select emp_id empId,emp_name empName,age,gender from t_emp where emp_id = #{empId} 
    </select>

第二种方式:在mybatis核心配置文件中设置全局配置来自动将下划线映为驼峰

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <!--将下划线映射为驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>
    <select id="getEmpByEmpIdOld" resultType="Emp">
        select * from t_emp where emp_id = #{empId}
    </select>

第三种方式:使用resultMap自定义映射


        //resultMap:设置自定义的映射关系
        //id:唯一标识
        //type:处理映射关系的实体类类型
        //常用的标签:
        //-id:处理主键和实体类中属性的类型
        //-result:处理普通字段和实体类中属性的映射关系
            //column:设置映射关系中的字段名,必须是sql查询出的某个字段
            //property:设置映射关系中的属性的属性名,必须是处理

    <resultMap id="empResultMap" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
    </resultMap>

    <select id="getEmpByEmpId" resultMap="empResultMap">
        select * from t_emp where emp_id = #{empId}
    </select>

版权声明:本文为qq_47637405原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。