失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Mybatis处理字段名和属性名不一致的几种方法

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

时间:2020-01-01 10:32:37

相关推荐

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 configurationPUBLIC "-////DTD Config 3.0//EN""/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>

如果觉得《Mybatis处理字段名和属性名不一致的几种方法》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。