MyBatis简介
了解了MyBatis那么我们就来看看在Java中如何使用MyBatis做一对一,一对多,多对一查询吧。
java实体类对象
public class Teacher {
private Integer id;
private String name;
private List<Student> students;
//......此处省略get,set方法
}
public class Student{
private Integer id;
private String name;
private Teacher teacher ;
//......此处省略get,set方法
}
Java Dao层代码
/**
*一对一:查某个学生信息并且查出他的老师
*/
Student queryStudentInfoById(@Param("id") Integer id);
/**
*一对多: 查某个老师并且查出老师所有的学生
*/
Teacher queryTeacherInfoById(@Param("id") Integer id);
/**
*多对一:查询所有同学并且查出同学对应的老师
*/
List<Student> queryStudentInfo();
一对一:查某个学生信息并且查出他的老师
<resultMap id="resultMap" type="com.test.Student">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<association property="teacher" javaType="ArrayList" ofType="com.test.Student" select="getTeacherInfoByTeacherId" column="teacher_id"/>
</resultMap>
<select id="queryStudentInfoById" resultType="com.test.Student">
SELECT id,name,teacher_id FROM student WHERE id =
</select>
<select id="getTeacherInfoByTeacherId" resultType="com.test.Teacher">
select id,name from teacher where id =
</select>
一对多: 查某个老师并且查出老师所有的学生
<resultMap id="resultMap" type="com.test.Teacher">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<collection property="students" javaType="ArrayList" ofType="com.test.Student" select="getStudentInfoByTeacherId" column="id"/>
</resultMap>
<select id="queryTeacherInfoById" resultType="com.test.Teacher">
SELECT id,name FROM teacher where id =
</select>
<select id="getStudentInfoByTeacherId" resultType="com.test.Student">
select id,name from student where teacher_id =
</select>
多对一:查询所有同学并且查出同学对应的老师
<resultMap id="resultMap" type="com.test.Student">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<association property="teacher" javaType="ArrayList" ofType="com.test.Student" select="getTeacherInfoByTeacherId" column="teacher_id"/>
</resultMap>
<select id="queryStudentInfo" resultType="com.test.Student">
SELECT id,name FROM student
</select>
<select id="getTeacherInfoByTeacherId" resultType="com.test.Teacher">
select id,name from teacher where id =
</select>
本文分享自微信公众号 - JAVA开发者课堂(leechence)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
来源:oschina
链接:https://my.oschina.net/u/4007900/blog/4474605