这篇文章主要介绍“MyBatis中一对一,一对多,多对一的用法”,在日常操作中,相信很多人在MyBatis中一对一,一对多,多对一的用法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”MyBatis中一对一,一对多,多对一的用法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
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 = #{id}
</select>
<select id="getTeacherInfoByTeacherId" resultType="com.test.Teacher">
select id,name from teacher where id = #{teacher_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 = #{id}
</select>
<select id="getStudentInfoByTeacherId" resultType="com.test.Student">
select id,name from student where teacher_id = #{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 = #{teacher_id}
</select>
到此,关于“MyBatis中一对一,一对多,多对一的用法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。