本讲讲述另一种关联一对一的映射方法,这种是推荐使用的最常用的方法。
工程目录:
与前一讲相比,增加了AddressMapper.java 和AddressMapper.xml两个文件:
AddressMapper.java:
package com.java1234.mappers;
import com.java1234.model.Address;
public interface AddressMapper {
public Address findAddressById(Integer id);
}
AddressMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.java1234.mappers.AddressMapper">
<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="findAddressById" resultMap="addressResult">
select * from t_address where id=#{id}
</select>
</mapper>
StudentMapper.java中内容没变:
package com.java1234.mappers;
import java.util.List;
import com.java1234.model.Student;
public interface StudentMapper {
public int add(Student student);
public int delete(Integer id);
public int update(Student student);
public Student getStudentById(Integer id);
public List<Student> getAllStudents();
public Student findStudentWithAddress(Integer id);
}
StudentMapper.xml中内容修正如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.java1234.mappers.StudentMapper">
<insert id="add" parameterType="Student" >
insert into t_student values(null,#{name},#{age})
</insert>
<delete id="delete" parameterType="Integer">
delete from t_student where id=#{id}
</delete>
<update id="update" parameterType="Student">
update t_student set name=#{name},age=#{age} where id=#{id}
</update>
<select id="getStudentById" parameterType="Integer" resultType="Student">
select * from t_student where id=#{id}
</select>
<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.findAddressById"/>
</resultMap>
<select id="getAllStudents" resultMap="StudentResult">
select * from t_student
</select>
<select id="findStudentWithAddress" resultMap="StudentResult" parameterType="Integer">
select * from t_student t1,t_address t2 where t1.addressId=t2.id and t2.id=#{id}
</select>
</mapper>
其中<association property="address" column="addressId" select="com.java1234.mappers.AddressMapper.findAddressById"/>里面的
column=“addressId”中的“addressId“是t_student表中的字段addressId,属于逻辑意义上的外键,对应于t_address表中的主键“id”。
测试:
结果: