目录
方式二:在resultMap使用association标签(一对一)
一、写在前面
在MyBatis 的全局配置文件中我们可以通过在settings标签中设置
<setting name="mapUnderscoreToCamelCase" value="true"/>来开启驼峰命名法,实现数据库中的字段名与JavaBean 中属性的关系映射。
在数据库中一般使用单词来定义列名,多个列名之间用’ _ ‘分隔开,比如department_name,在JavaBean 中一般使用驼峰命名来定义属性,所以会定义为departmentName。在默认不开启驼峰命名法的情况下,它们之间是不能够实现关系映射的,在开启对驼峰命名法的支持后,MyBatis 会对数据库中的字段进行驼峰命名转换。
但是有的时候,开启驼峰命名法也不能完成映射,比如数据库字段dept_name对应JavaBean 中的departmentName,这时候就需要我们自定义resultMap关系映射。
二、resultMap
自定义映射规则
- 使用
resultMap
实现数据库中的dept_name
字段与JavaBean 中的departmentName
的关系映射。
mapper接口
// 通过id 查询部门信息,返回的是一个Department 对象
Department getDeptById(Integer id);
sql:
<!--
先通过resultMap 定义映射规则
id:当前命名空间中的一个唯一标识,用于标识一个resultMap
type:类的完全限定名, 或者一个类型别名,也就是返回的对应JavaBean 类型
-->
<resultMap id="BaseDeptResultMap" type="com.jas.mybatis.bean.Department">
<!--
<id>:与下面<result>标签的区别是可以用于提升性能,所以这里用<id>标签来定义主键的映射关系
column:数据库中对应的字段名
property:对应JavaBean 的属性名
因为可以实现自动映射,所以<id column="id" property="id"/> 在这里也可以省略,
如果开启了驼峰命名法,对应的映射转换也可以省略
-->
<id column="id" property="id"/>
<result column="dept_name" property="departmentName"/>
</resultMap>
<select id="getDeptById" resultMap="BaseDeptResultMap">
SELECT * FROM t_dept WHERE id = #{id}
</select>
三、resultMap
实现关联映射
- 在根据
id
查询员工信息的时候,把员工所在的部门信息也查出来。
Employee员工类:
public class Employee {
private Integer id;
private String username;
private Character gender;
private String email;
//在Employee 类中定义一个Department 对象,用来封装员工的部门信息
private Department department;
// 省略get、set 与toString 方法
}
Department部门类:
public class Department {
private Integer id;
private String departmentName;
}
mapper接口:
// 根据id 查出员工的信息并把对应的部门信息也查询出来
Employee getEmpAndDeptById(Integer id);
sql:
方式一:
<resultMap type="com.jas.mybatis.bean.Employee" id="BaseEmployeeResultMap">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<!--
通过下面两个列名获得数据将封装成Department 对象
直接通过属性名.属性名的方式指定映射的关系
-->
<result column="d_id" property="department.id"/>
<result column="dept_name" property="department.departmentName"/>
</resultMap>
<select id="getEmpAndDeptById" resultMap="BaseEmployeeResultMap">
SELECT e.id, e.username, e.gender, e.email, e.d_id, d.dept_name
FROM t_employee e LEFT JOIN t_dept d
ON (e.d_id = d.id)
WHERE e.id = #{id}
</select>
方式二:在resultMap
使用association
标签(一对一)
<resultMap type="com.jas.mybatis.bean.Employee"