mybatis:级联(一对一)

以下知识来源说明:http://www.java1234.com/

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>

猜你喜欢

转载自blog.csdn.net/m0_38084243/article/details/82378460