与上次唯一不同的一下几个类
Department.java
package com.cn.zhu.bean;
public class Department {
private Integer id;
private String departmentName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [departmentName=" + departmentName + ", id=" + id
+ "]";
}
}Employee.java
package com.cn.zhu.bean;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
private Department dept;
public Employee() {
super();
// TODO Auto-generated constructor stub
}
public Employee(Integer id, String lastName, String email, String gender) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee [email=" + email + ", gender=" + gender + ", id=" + id
+ ", lastName=" + lastName + "]";
}
}
EmployeeMapperPlus.java
package com.cn.mybatis.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;
import com.cn.zhu.bean.Employee;
public interface EmployeeMapperPlus {
public Employee getEmpById(Integer id);
public Employee getEmpAndDept(Integer id);
}
EmployeeMapperPlus.xml
SELECT e.id id,e.last_name last_name ,e.gender gender,e.d_id d_id,
d.id did,d.dept_name dept_name from tbl_employee e,tbl_dept d
where e.d_id=d.id and e.id=#{id}
以上是两种映射封装结果
增加EmployeeMapperPlus.xml 后,一定要在mybatis-config.xml里加上这个配置文件的声明,
另外sql语句一定要正确,可以先在navict数据库图形化管理工具中,测试sql
下面编写测试类(这里直接写测试方法吧):详细请看映射一
@Test
public void test05() throws IOException{
SqlSessionFactory sqlsessionFactory=getSqlSessionFactory();
// 1 获取到的sqlsession不会自动提交数据
SqlSession openSession=sqlsessionFactory.openSession();
try{
EmployeeMapperPlus mapper=openSession.getMapper(EmployeeMapperPlus.class);
Employee empAndDept=mapper.getEmpAndDept(1);
System.out.println(empAndDept);
System.out.println(empAndDept.getDept());
}finally{
openSession.commit();
}
}
测试完成
接下来,会写分布查询,请看下一篇文章