提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
mybatis学习记录
06. MyBatis 字段名与属性名不一致时的处理
提示:以下是本篇文章正文内容,下面案例可供参考
创建MySQL表
mybatis库,新建t_dept表(字段:int:did(主键),varchar: dept_name);
新建t_emp表(字段:int:eid(主键),varchar: emp_name,int:age,varchar: sex,varchar: email,int:did)
创建相应实体类
/**
* @Description: 部门信息实体类
* @Author: zqf
* @Date: 2022/3/2 14:49
* @Version 1.0
**/
public class Dept {
private Integer did;
private String deptName;
private List<Emp> emps;
//有参无参构造,Getter,Setter,toString()省略
}
/**
* @Description: 员工信息实体类
* @Author: zqf
* @Date: 2022/3/2 14:49
* @Version 1.0
**/
public class Emp implements Serializable {
private Integer eid;
private String empName;
private Integer age;
private String sex;
private String email;
private Dept dept;
//有参无参构造,Getter,Setter,toString()省略
}
字段名与属性名不一致时的处理
测试方法:
@Test
public void testGetAllEmp() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
List<Emp> list = mapper.getAllEmp();
list.forEach(emp -> System.out.println(emp));
}
mapper接口:
public interface EmpMapper {
List<Emp> getAllEmp();
}
- a>通过设置字段名别名,与属性名一致
映射文件:
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultType="Emp">
select eid,emp_name empName,age,sex,email from t_emp
</select>
- b>通过mybatis-config设置全局配置mapUnderscoreToCamelCase设为true,将_自动映射为驼峰
映射文件:
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultType="Emp">
select * from t_emp
</select>
mybatis全局配置:
通过mybatis-config设置全局配置mapUnderscoreToCamelCase设为true,将_自动映射为驼峰
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
- c>通过resultMap设置自定义映射关系
子标签:id设置主键的映射关系,result设置普通字段映射关系
resultMap:设置自定义映射(通常用于处理一对多或多对一的映射关系)
属性:
id:表示自定义映射的唯一标识
type:查询的数据要映射的实体类的类型
子标签:
id:设置主键的映射关系
result:设置普通字段的映射关系
association:设置多对一的映射关系
collection:设置一对多的映射关系
属性:
property:设置映射关系中实体类中的属性名
column:设置映射关系中表中的字段名,必须是sql语句查询出来的字段名
映射文件:
<resultMap id="empResultMap" type="Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
</resultMap>
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultMap="empResultMap">
select * from t_emp
</select>