MyBatis 关系映射
对象级联(一对一)四种方式(有两张表,一个学生表,一个地址表,一个学生对应一个地址)
实体
/** *简化写 **/ public class Student { private Integer id; private String name; private Integer age; private Address address; } public class Address { private Integer id; private String sheng; private String shi; private String qu; }
1.0 (不推荐使用)
<resultMap type="Student" id="StudentResult"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <result property="address.id" column="addressId"/> addressId是学生表的外键 <result property="address.sheng" column="sheng"/> <result property="address.shi" column="shi"/> <result property="address.qu" column="qu"/> </resultMap>
2.0(不推荐)
<resultMap type="Address" id="AddressResult"> <result property="id" column="id"/> <result property="sheng" column="sheng"/> <result property="shi" column="shi"/> <result property="qu" column="qu"/> </resultMap> <resultMap type="Student" id="StudentResult"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <association property="address" resultMap="AddressResult"/> </resultMap>
3.0(不推荐)
<resultMap type="Student" id="StudentResult"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <association property="address" javaType="Address"> <result property="id" column="id"/> <result property="sheng" column="sheng"/> <result property="shi" column="shi"/> <result property="qu" column="qu"/> </association> </resultMap>
4.0(推荐)
<resultMap type="Student" id="StudentResult"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <association property="address" column="addressId" select="com.java.mappers.AddressMapper.findById"></association> addressId外键 </resultMap>
package com.java.mappers; import com.java.model.Address; public interface AddressMapper { public Address findById(Integer id); }