mybatis的关联查询,学生表和班级表 ,比如要查询 学生所在的 班级
1.Entity (注意学生类中要有班级ClassRoom 的对象属性)
@Data
public class Student {
private Integer id;
private String name;
private ClassRoom classRoom;
}
@Data
public class ClassRoom {
private Integer id;
private String name;
}
2.mapper接口,根据学生 id 查询学生信息和所在班级
public List<Object> selectGuanLian(Integer id);
3.sql映射文件(注意方式一中的property要和学生类pojo中的对象属性名称一致)
<?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.example.mybatis.mybatis2.dao.StudentMapper">
<resultMap id="BaseResultMap" type="com.example.mybatis.mybatis2.bean.Student">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<!--方式一:级联方式关联-->
<!--<result column="cd" jdbcType="INTEGER" property="classRoom.id" />-->
<!--<result column="croom" jdbcType="VARCHAR" property="**classRoom.name" />-->
<!--方式二:映射方式关联-->
<association property="classRoom" javaType="com.example.mybatis.mybatis2.bean.ClassRoom">
<id column="id" jdbcType="INTEGER" property="id"/>
<id column="croom" jdbcType="VARCHAR" property="name"/>
</association>
</resultMap>
<!--//关联查询-->
<select id="selectGuanLian" resultMap="BaseResultMap">
SELECT s.id , s.name , c.id cd , c.classname croom from student s ,classroom c
where s.cid = c.id and s.id =#{id};
</select>
</mapper>