现在有一数据库mybatis,两张数据表
tbl_department
tbl_employee
其中tbl_employee表中的d_id关联tbl_department表中的id字段
Employee.java
代码语言:javascript复制public class Employee {
private Integer id;
private String lastName;
private String gender;
private String email;
Department dept;
}
Department.java
代码语言:javascript复制public class Department {
private Integer id;
private String deptName;
}
(省略了getters和setters以及toString方法)
EmployeeMapper.java
代码语言:javascript复制 public Employee getEmpAndDept(Integer id);
EmployeeMapper.xml
代码语言:javascript复制 <resultMap type="com.gong.mybatis.bean.Employee" id="MySimpleMap">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<result column="did" property="dept.id"/>
<result column="dept_name" property="dept.deptName"/>
</resultMap>
<select id="getEmpAndDept" resultMap="MySimpleMap">
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进行级联映射。
最后进行测试:
代码语言:javascript复制package com.gong.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.gong.mybatis.bean.Employee;
import com.gong.mybatis.dao.EmployeeMapperPlus;
public class TestMybatis2 {
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(is);
}
@Test
public void test() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try {
EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
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,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=?; (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=开发部]
说明关联查询是成功的。