1、映射接口
- public interface ClazzMapper
- {
-
- @Select("SELECT * FROM tb_clazz WHERE ID = #{id}")
- @Results(
- { @Result(id = true, column = "id", property = "id"), @Result(column = "code", property = "code"),
- @Result(column = "name", property = "name"),
- @Result(column = "id", property = "students", many = @Many(select = "cn.mybatis.mydemo5.mapper.StudentMapper.selectByClazzId", fetchType = FetchType.LAZY)) })
- Clazz selectById(Integer id);
- }
- public interface StudentMapper
- {
-
- @Select("SELECT * FROM tb_student WHERE CLAZZ_ID = #{id}")
- @Results(
- { @Result(id = true, column = "id", property = "id"), @Result(column = "name", property = "name"),
- @Result(column = "sex", property = "sex"), @Result(column = "age", property = "age") })
-
- List<Student> selectByClazzId(Integer clazz_id);
- }
2、引入映射接口
- <mappers>
- <mapper class="cn.mybatis.mydemo5.mapper.ClazzMapper" />
- <mapper class="cn.mybatis.mydemo5.mapper.StudentMapper" />
- </mappers>
3、测试代码
- public class App
- {
- public static void main(String[] args) throws Exception
- {
-
- SqlSession session = MySqlSessionFactory.getSqlSession();
-
- ClazzMapper cm = session.getMapper(ClazzMapper.class);
-
- Clazz clazz = cm.selectById(1);
-
- System.out.println(clazz.getId() + " " + clazz.getCode() + " " + clazz.getName());
-
- clazz.getStudents().forEach(student -> System.out.println(student));
-
- session.commit();
-
- session.close();
- }
- }
诚恳拜师