mybatis字段名和属性名不一致

若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性
名符合Java的规则(使用驼峰)。此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系。

第一种处理方法:为字段起别名,使之与属性名一致

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

第二种处理方法:可以在MyBatis的核心配置文件中设置一个全局配置、mapUnderscoreT-oCamelCase,可以在查询表中数据时,自动将_类型的字段名转换为驼峰。

例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为
userName

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

第三种方法是使用resultmap来处理

resultMap:设置自定义的映射关系
id:唯一标识
type:处理映射关系的实体类的类型
常用的标签:
id:处理主键和实体类中属性的映射关系
result:处理普通字段和实体类
中属性的映射关系
association:处理多对一的映射关系(处理实体类类型的属性)
collection:处理一对多的映射关系(处理集合类型的属性)
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>

    <!--Emp getEmpByEmpId(@Param("empId") Integer empId);-->
    <select id="getEmpByEmpId" resultMap="empResultMap">
        select * from t_emp where emp_id = #{empId}
    </select>

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值