MyBatis中使用association标签来解决一对一的关联查询,association标签可用的属性如下:
- property:对象属性的名称
- javaType:对象属性的类型
- column:所对应的外键字段名称
- select:使用另一个查询封装的结果
entity类:Student
public class Student {
private Integer id;
private String name;
private Integer age;
private Address address;
Getters and Setters……
toString……
}
entity类:Address
public class Address {
private Integer id;
private String sheng;
private String shi;
private String qu;
Getters and Setters……
toString……
}
Mapping:方法一
<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"/>
<result property="address.sheng" column="sheng"/>
<result property="address.shi" column="shi"/>
<result property="address.qu" column="qu"/>
</resultMap>
Mapping:方法二
<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>
Mapping:方法三
<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>
Mapping:方法四
StudentMapper.xml
<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.java1234.mappers.AddressMapper.findById"></association>
</resultMap>
<select id="findStudentWithAddress" resultMap="StudentResult" parameterType="Integer">
select * from t_student t1,t_address t2 where t1.addressId=t2.id and t1.id=#{id}
</select>
AddressMapper.xml
<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>
<select id="findById" parameterType="Integer" resultType="Address">
select * from t_address where id=#{id}
</select>