赞
踩
需要使用`resultMap`来自定义映射规则
- <select id="getTeacherByTid" resultMap="asTeacher">
- select *, teacher.name as tname from student inner join teach on student.sid = teach.sid
- inner join teacher on teach.tid = teacher.tid where teach.tid = #{tid}
- </select>
-
- <resultMap id="asTeacher" type="Teacher">
- <id column="tid" property="tid"/>
- <result column="tname" property="name"/>
- <collection property="studentList" ofType="Student">
- <id property="sid" column="sid"/>
- <result column="name" property="name"/>
- <result column="sex" property="sex"/>
- </collection>
- </resultMap>
- @Data
- public class Teacher {
- int tid;
- String name;
- List<Student> studentList;
- }
`id`标签用于在多条记录中辨别是否为同一个对象的数据,比如上面的查询语句得到的结果中,`tid`这一行始终为`1`,因此所有的记录都应该是`tid=1`的教师的数据,而不应该变为多个教师的数据,如果不加id进行约束,那么会被识别成多个教师的数据
通过使用collection来表示将得到的所有结果合并为一个集合,比如上面的数据中每个学生都有单独的一条记录,因此tid相同的全部学生的记录就可以最后合并为一个List
每个学生都有一个对应的老师,多个学生对应一个老师
- @Data
- @Accessors(chain = true)
- public class Student {
- private int sid;
- private String name;
- private String sex;
- private Teacher teacher;
- }
-
- @Data
- public class Teacher {
- int tid;
- String name;
- }
需要使用`resultMap`来自定义映射规则
- <resultMap id="test2" type="Student">
- <id column="sid" property="sid"/>
- <result column="name" property="name"/>
- <result column="sex" property="sex"/>
- <association property="teacher" javaType="Teacher">
- <id column="tid" property="tid"/>
- <result column="tname" property="name"/>
- </association>
- </resultMap>
- <select id="selectStudent" resultMap="test2">
- select *, teacher.name as tname from student left join teach on student.sid = teach.sid
- left join teacher on teach.tid = teacher.tid
- </select>
在获取`SqlSession`关闭自动提交来开启事务模式,和JDBC其实都差不多
SqlSession sqlSession = MybatisUtil.getSession(false)
在关闭自动提交后,我们的内容是没有进入到数据库的,在事务提交后,我们的内容才会被写入到数据库中。
sqlSession.commit();
- try (SqlSession sqlSession = MybatisUtil.getSession(false)){
- TestMapper testMapper = sqlSession.getMapper(TestMapper.class);
-
- testMapper.addStudent(new Student().setSex("男").setName("小王"));
-
- testMapper.selectStudent().forEach(System.out::println);
- sqlSession.rollback();
- sqlSession.commit();
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。