上一节,已经把实体类和配置文件都写过了,这节课直接添加几个方法吧
在DeptMapper.xml文件中添加
<!-- 多表查询(1对多) ,通过部门编号,查询出部门所在的员工姓名,部门名,部门编号 --> <select id="selectByDeptno" resultMap="deptResult"> select ename,dept.deptno,dname from dept join emp on dept.deptno=emp.deptno where dept.deptno=#{deptno} </select> <!-- one 方 --> <resultMap type="Dept" id="deptResult"> <!-- id指定主键的相关信息(列名、属性名) --> <id property="deptno" column="deptno" /> <!-- result定义除了主键列之外的其他字段 --> <result property="dname" column="dname" /> <collection property="emps" ofType="Emp" resultMap="empResult" foreignColumn="deptno" /> </resultMap> <!-- many方 --> <resultMap id="empResult" type="Emp"> <id property="empno" column="empno" /> <result property="ename" column="ename" /> </resultMap> <!--一对一查询 --> <!-- 通过员工编号,查询该员工姓名、所在部门名称 --> <select id="selectByEmpno" resultMap="empResult1"> select ename,dept.deptno,dname from emp join dept on emp.deptno=dept.deptno where emp.empno=#{empno} </select> <resultMap id="empResult1" type="Emp"> <id property="empno" column="empno" /> <result property="ename" column="ename" /> <association property="dept" javaType="Dept" foreignColumn="deptno" resultMap="deptResult1"></association> </resultMap> <resultMap id="deptResult1" type="Dept"> <!-- id指定主键的相关信息(列名、属性名) --> <id property="deptno" column="deptno" /> <!-- result定义除了主键列之外的其他字段 --> <result property="dname" column="dname" /> </resultMap>
2. mapper接口
public interface DeptMapper { public Dept selectByDeptno(int deptno); public Emp selectByEmpno(int empno); }
3.测试方法
public class DeptTest { public static void main(String[] args) throws IOException { // 指定mybatis配置文件路径和文件名 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); SqlSession session = sqlSessionFactory.openSession(); try { // session.selectOne(配置文件中namespace.id,传入参数的值) //通过接口,调用方法(接口名和namespace名称保持一致,id和方法名保持一致) DeptMapper mapper = session.getMapper(DeptMapper.class); //一对多查询 Dept dept=mapper.selectByDeptno(10); System.out.println(dept.getDeptno()+dept.getLoc()+dept.getDname()); List<Emp> list=dept.getEmps(); for (Emp emp : list) { System.out.println(emp.getEname()); } //一对一查询 Emp emp=mapper.selectByEmpno(7499); System.out.println("部门编号:"+emp.getDept().getDeptno()+"部门名字:"+emp.getDept().getDname()+"员工名字:"+emp.getEname()); } } finally { session.close(); } } }