Windows 10 企业版 LTSC 21H2 MySQL 5.7.40 Java 1.8 Maven 3.6.3 MyBatis 3.5.6
1 基本映射
默认情况下,MyBatis会自动将列名和Java属性名映射。
在配置文件中配置全局参数开启驼峰命名自动映射后,MyBatis会自动将列名转换为驼峰命名。
2 自定义映射
2.1 对一
2.1.1 XML配置
使用association标签配置对一关联关系。
常用属性:
属性名
作用
取值
property
指定实体中关联对象的属性名
属性名
javaType
指定关联对象的全类名
全类名
column
传递给子查询的字段名
字段名
select
指定子查询的Mapper方法的全类名
全类名
fetchType
指定加载策略(覆盖全局延迟加载配置)
默认为eager表示立即加载,设置为lazy表示延迟加载
resultMap
指定关联对象的自定义ResultMap的ID值
ResultMap的ID值
通过级联属性获取关联对象:
xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<resultMapid="userWithHome"type="com.example.pojo.User"> <idcolumn="id"property="id"/> <resultcolumn="name"property="name"/> <resultcolumn="age"property="age"/> <resultcolumn="email"property="email"/> <!-- 配置对一关联 --> <associationproperty="home"javaType="com.example.pojo.Home"> <idcolumn="home_id"property="id"/> <resultcolumn="home_uid"property="uid"/> <resultcolumn="home_name"property="name"/> <resultcolumn="home_phone"property="phone"/> </association> </resultMap> <selectid="selectUserListWithHome"resultMap="userWithHome"> SELECT u.*, h.id AS home_id, h.uid AS home_uid, h.name AS home_name, h.phone AS home_phone FROM user u LEFT JOIN home h ON u.id = h.uid </select>
通过子查询获取关联对象:
xml
1 2 3 4 5 6 7 8 9 10 11
<resultMapid="userWithHome"type="com.example.pojo.User"> <idcolumn="id"property="id"/> <resultcolumn="name"property="name"/> <resultcolumn="age"property="age"/> <resultcolumn="email"property="email"/> <!-- 配置对一关联,指定子查询,设置延迟加载 --> <associationcolumn="id"property="home"select="com.example.mapper.HomeMapper.selectHomeById"fetchType="lazy"/> </resultMap> <selectid="selectUserListWithHome"resultMap="userWithHome"> SELECT * FROM user u </select>
<resultMapid="userWithWork"type="com.example.pojo.User"> <idcolumn="id"property="id"/> <resultcolumn="name"property="name"/> <resultcolumn="age"property="age"/> <resultcolumn="email"property="email"/> <!-- 配置对一关联 --> <collectionproperty="workList"ofType="com.example.pojo.Work"> <idcolumn="work_id"property="id"/> <resultcolumn="work_uid"property="uid"/> <resultcolumn="work_name"property="name"/> <resultcolumn="work_phone"property="phone"/> </collection> </resultMap> <selectid="selectUserListWithWork"resultMap="userWithWork"> SELECT u.*, w.id AS work_id, w.uid AS work_uid, w.name AS work_name, w.phone AS work_phone FROM user u LEFT JOIN work w ON u.id = w.uid </select>
通过子查询获取关联对象:
xml
1 2 3 4 5 6 7 8 9 10 11
<resultMapid="userWithWork"type="com.example.pojo.User"> <idcolumn="id"property="id"/> <resultcolumn="name"property="name"/> <resultcolumn="age"property="age"/> <resultcolumn="email"property="email"/> <!-- 配置对一关联,指定子查询,设置延迟加载 --> <collectioncolumn="id"property="workList"select="com.example.mapper.WorkMapper.selectWorkListByUid"fetchType="lazy"/> </resultMap> <selectid="selectUserListWithWork"resultMap="userWithWork"> SELECT * FROM user u </select>
条