工程结构
一对一关系实现
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="findById" parameterType="Integer" resultType="Address">
select * from t_address where id=#{id}
</select>
</mapper>
AddressMapper.java
public interface AddressMapper {
public Address findById(Integer id);
}
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="address" 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>
<!-- 此处省略Student类的增删改查 -->
StudentMapper.java新增方法findStudentWithAddress
public Student findStudentWithAddress(Integer id);
测试类
@Test
public void testFindStudentWithAddress() {
logger.info("查询学生(带地址)");
Student student=studentMapper.findStudentWithAddress(2);
System.out.println(student);
}
一对多关系实现
一个年级中有很多学生、
GradeMapper.xml
<resultMap type="Grade" id="GradeResult">
<result property="id" column="id"/>
<result property="gradeName" column="gradeName"/>
<!-- Grade类中有属性List<Student> students -->
<collection property="students" column="id" select="com.java1234.mappers.StudentMapper.findByGradeId"></collection>
</resultMap>
<select id="findById" parameterType="Integer" resultMap="GradeResult">
select * from t_grade where id=#{id}
</select>
GradeMapper.java
public interface GradeMapper {
public Grade findById(Integer id);
}
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>
<association property="grade" column="gradeId" select="com.java1234.mappers.GradeMapper.findById"></association>
</resultMap>
<select id="findByGradeId" resultMap="StudentResult" parameterType="Integer">
select * from t_student where gradeId=#{gradeId}
</select>
StudentMapper.java新增方法findByGradeId
public Student findByGradeId(Integer gradeId);
Test
@Test
public void testFindGradeWithStudents() {
logger.info("查询年级(带学生)");
Grade grade=gradeMapper.findById(1);
System.out.println(grade);
}