Mybatis级联查询-associatio&和collection (多对一&一对多)
一对多和多对一
Student
package com.southwind.entity;
import lombok.Data;
@Data
public class Student {
private long id;
private String name;
private Classes classes;
}
Classes
package com.southwind.entity;
import lombok.Data;
import java.util.List;
@Data
public class Classes {
private long id;
private String name;
private List<Student> students;
}
多对一:
StudentRepository
package com.southwind.repository;
import com.southwind.entity.Student;
public interface StudentRepository {
public Student findById(long id);
}
StudentRepository.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.southwind.repository.StudentRepository">
<resultMap id="studentMap" type="com.southwind.entity.Student">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<association property="classes" javaType="com.southwind.entity.Classes">
<id column="cid" property="id"></id>
<result column="cname" property="name"></result>
</association>
</resultMap>
<select id="findById" parameterType="long" resultMap="studentMap">
select s.id,s.name,c.id as cid,c.name as cname
from student s,classes c
where s.id = #{id} and s.cid = c.id
</select>
</mapper>
type是查询的主类所在的位置,id是主键,result是其他属性值,column是sql语句中的字段,property是实体类中映射的属性名,association表示的是关联,javaType是所在的类,collection表示的是集合,ofType是集合中元素的类型
一对多
ClassesRepository
package com.southwind.repository;
import com.southwind.entity.Classes;
public interface ClassesRepository {
public Classes findById(long id);
}
ClassesRepository.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.southwind.repository.ClassesRepository">
<resultMap id="classesMap" type="com.southwind.entity.Classes">
<id column="cid" property="id"></id>
<result column="cname" property="name"></result>
<!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
<collection property="students" ofType="com.southwind.entity.Student">
<id column="id" property="id"/>
<result column="name" property="name"/>
</collection>
</resultMap>
<select id="findById" parameterType="long" resultMap="classesMap">
select s.id,s.name,c.id as cid,c.name as cname
from student s,classes c
where c.id = #{id} and s.cid = c.id
</select>
</mapper>

浙公网安备 33010602011771号