MyBatis多对一关联查询
类似于一对一查询
修改Student实体类
添加一个MyClass类型的属性
package com.h3c.bean;
public class Student {
private int id;
private String name;
private int age;
private double score;
//所在班级
private MyClass myclass;
//省略constructor、getter、setter、toString方法
//注意constructor中的无参构造方法不能少
}
dao层接口
package com.h3c.dao;
public interface studentDao {
//多对一关联查询
Student selectStudentById(int id);
//一对多
List<Student> selectStudents();
}
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.h3c.dao.MyClassDao">
<resultMap id="StudentMap" type="student">
<!--student中的基本属性-->
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<result column="score" property="score"/>
<!--关联属性的映射关系-->
<association property="myClass" javaType="myClass">
<id column="id" property="id"/>
<result column="name" property="name"/>
</association>
</resultMap>
<select id="selectStudentById" resultMap="StudentMap">
SELECT s.id, s.name, s.age, s.score, c.id, c.name
FROM t_class c, t_student s
WHERE c.id = s.cid and c.id=#{id}
</select>
<select id="selectStudents" resultMap="StudentMap">
SELECT s.id, s.name, s.age, s.score, c.id, c.name
FROM t_class c, t_student s
WHERE c.id = s.cid
</select>
</mapper>
- 方式二:
<?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.h3c.dao.MyClassDao">
<!-- 多对一查询 -->
<resultMap id="StudentMap" type="student">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<result column="score" property="score"/>
<!-- 跟一对一一样用association标签,实体类定义的成员,要跟数据库字段名对应上 -->
<association property="myClass"
column="cid"
<!-- 用接口里定义的方法,根据student表中的major字段查出对应数据 -->
select="com.h3c.dao.StudentDao.selectClassById"/>
</resultMap>
<resultMap id="ClassMap" type="myClass">
<id column="id" property="id"/>
<result column="name" property="name"/>
</resultMap>
<!-- 查全部 -->
<select id="selectStudentById" resultMap="StudentMap" >
select id, name, age, score, cid from t_student where id=#{id}
</select>
<!-- 根据id查班级 -->
<select id="selectClassById" parameterType="int" resultMap="ClassMap">
select id, name from t_class where id=#{id}
</select>
</mapper>