现在有一数据库mybatis,两张数据表
tbl_department
tbl_employee
其中tbl_employee表中的d_ID关联tbl_department表中的ID字段
Employee.java
public class Employee { private Integer ID; String lastname; String gender; String email; Department dept;}
Department.java
Department { String deptname;}
(省略了getters和setters以及toString方法)
EmployeeMapper.java
public Employee getEmpAndDept(Integer ID);
EmployeeMapper.xml
<resultMap type="com.gong.mybatis.bean.Employee" ID="MySimpleMap"> ID column="ID" property="ID"/> result ="last_name"="lastname"="gender"="gender"="email"="email"="dID"="dept.ID"="dept_name"="dept.deptname"/> </resultMap> select ID="getEmpAndDept" resultMap> SELECT e.ID,e.last_name,e.gender,e.email,d.dept_name,d.ID dID FROM tbl_employee e,tbl_department d WHERE e.d_ID = d.ID and e.ID=#{ID}; select>
说明:可以支持级联属性映射,由于我们在select标签中为tbl_department中的ID取了别名,因此可以直接在resultMap中对dID进行级联映射。
最后进行测试:
package com.gong.mybatis.test;import java.io.IOException; java.io.inputStream; java.util.Map; org.apache.ibatis.io.Resources; org.apache.ibatis.session.sqlSession; org.apache.ibatis.session.sqlSessionFactory; org.apache.ibatis.session.sqlSessionFactoryBuilder; org.junit.Test; com.gong.mybatis.bean.Employee; com.gong.mybatis.dao.EmployeeMapperPlus; TestMybatis2 { public sqlSessionFactory getsqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; inputStream is = Resources.getResourceAsstream(resource); return new sqlSessionFactoryBuilder().build(is); } @Test voID test() IOException { sqlSessionFactory sqlSessionFactory = getsqlSessionFactory(); sqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.); Employee employee = mapper.getEmpAndDept(3); System.out.println(employee); System.out.println(employee.getDept()); openSession.commit(); } finally { openSession.close(); } }}
输出:
DEBUG 01-20 12:15:43,557 ==> Preparing: SELECT e.ID,d.ID dID FROM tbl_employee e,tbl_department d WHERE e.d_ID = d.ID and e.ID=?; (BaseJdbcLogger.java:145)
DEBUG 01-20 12:15:43,611 ==> Parameters: 3(Integer) (BaseJdbcLogger.java:145)
DEBUG 01-20 12:15:43,652 <== Total: 1 (BaseJdbcLogger.java:145)
Employee [ID=3,lastname=小红,gender=0,email=xiaohong@qq.com,dept=Department [ID=1,deptname=开发部]]
Department [ID=1,deptname=开发部]
说明关联查询是成功的。
总结以上是内存溢出为你收集整理的mybatis文件映射之关联查询初探(一)全部内容,希望文章能够帮你解决mybatis文件映射之关联查询初探(一)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)