Mybatis下的数据库表自关联查询
2017-09-23 16:51
253 查看
简单粗暴点,直接上代码吧mysql创建一张表,表名prentice表中林朝英有两个徒弟,分别是小龙女和李莫愁。而小龙女有徒弟杨过,李莫愁有徒弟洪凌波。 现在需要通过pid查询出师傅所收的全部徒弟信息。1. 创建 Prentice实体类 (略)2. 创建PrenticeMapper接口package com.wl.mapper;import java.util.List;import com.wl.pojo.Prentice;//根据pid查询徒弟信息public interface PrenticeMapper {List<Prentice> selectPrenticeByPid(int pid);}3. 配置PrenticeMapper.xml文件<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- 查询师傅所带的徒弟 --><mapper namespace="com.wl.mapper.PrenticeMapper"><resultMap type="Prentice" id="prenticeMapper"><id column="id" property="id"/><result column="name" property="name"/><collection property="prentices"ofType="Prentice"select="selectPrenticeByPid"column="id"/></resultMap><select id="selectPrenticeByPid" resultMap="prenticeMapper">select id,name from prentice where pid=#{pid}</select></mapper>4. 工具类MybatisUtil及mybatis.xml 文件的配置此处就略写啦,相信大家都能搞定。下面就直接上测试5. 测试类public class TestPrentice {private PrenticeMapper mapper;private SqlSession sqlSession;@Beforepublic void Before(){sqlSession = MyBatisUtil.getSqlSession();mapper = sqlSession.getMapper(PrenticeMapper.class);}@Afterpublic void After(){if(sqlSession!= null){sqlSession.close();}}@Testpublic void selectPrenticeByPid(){List<Prentice> prentices = mapper.selectPrenticeByPid(1);for (Prentice prentice : prentices) {System.out.println(prentice);}}}经测试,小龙女及其徒弟杨过,李莫愁及其徒弟洪凌波都被打印在控制台~~~关于查询师傅及其徒弟的信息,在此就不贴出来啦~~~不足之处,欢迎指正!
相关文章推荐
- Mybatis关联查询,查询出的记录数量与数据库直接查询不一致,如何解决?
- Mybatis关联查询,查询出的记录数量与数据库直接查询不一致,如何解决?
- Mybatis关联查询和数据库不一致问题分析与解决
- Mybatis——关联查询
- mybatis对象之间映射关系以及数据库表建立的时候外键的添加
- 关于mybatis修改数据库信息,控制台能执行,数据库没变
- 写mybatis查询数据库涉及中文
- Hbase增删改查、关联查询、关系型数据库转化
- Spring Boot快速入门(五):使用MyBatis(注解形式)进行数据库操作
- Mybatis深入了解(六)----关联查询(高级映射)
- Mybatis 通用数据库接口 SqlMapper
- springMVC+mybatis+spring security<三>:使用数据库管理资源
- Mybatis连接mysql,数据库中字符乱码问题
- JAVA类获取mybatis的mapper进行数据库操作
- mybatis 数据库.xml中方法参考
- java客户端程序集成mybatis操作数据库
- 四、引入mybatis连接数据库(补充)
- mybatis“集合嵌套查询”和“集合嵌套结果”两种方法实现数据库一对多关系
- 数据库相关:Hibernate对多表关联查询
- 项目记录,Mybatis框架下批量修改数据库,你要绕过这些坑