mybatis中级联属性的方式封装查出的数据
Department实体类
Employee实体类
在mybatis中,先在实现数据库操作的xml配置文件中,进行数据绑定(其中注意属性的绑定一定要与自己实体类中的属性大小写一致)。
数据库操作接口
package day02_crud;
import java.util.List;
public interface EmployeeDao {
public List<Employee1> findPerson();//查找所有的员工
}
resultMap标签是进行自定义封装类型,其中的id作为唯一标识,type属性是封装目标值的类型,一定要写实体类的路径。其内部的id标签用作标记主键,result标签标记其他属性值。
association:联合标签,就是将实体类中级连属性进行封装。javaType属性值就是级连属性的实体类路径。(id、result属性的作用同上)
自定义封装类型写好了之后,就需要在select标签中,使用resultMap属性对自定义类型进行引用,其值就是自定义类型的id值。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="day02_crud.EmployeeDao">
<select id="findPerson" resultMap="EmployeeMap">
select e.ID,e.userName,e.email,e.gender,e.dName,e.birth,d.ID dId from employee e join department d on e.dName=d.dName
</select>
<resultMap id="EmployeeMap" type="day02_crud.Employee1">
<id property="ID" column="ID"/>
<result property="userName" column="userName"/>
<result property="email" column="email"/>
<result property="gender" column="gender"/>
<result property="birth" column="birth"/>
<association property="department" javaType="day02_crud.Department">
<id property="id" column="dId"/>
<result property="dName" column="dName"/>
</association>
</resultMap>
</mapper>
测试类:
package day02_crud;
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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class mybatisTest {
SqlSessionFactory sqlSessionFactory;
@Before
public void SqlsessionFactoryTest() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
//查找所有的员工
@Test
public void findAll(){
SqlSession sqlsession =sqlSessionFactory.openSession(true);
EmployeeDao employeeDao= sqlsession.getMapper(EmployeeDao.class);
try{
List<Employee1> employeeList=employeeDao.findPerson();
for ( Employee1 employee: employeeList
) {
System.out.println(employee);
}
}catch (Exception e){
e.printStackTrace();
}finally{
sqlsession.close();
}
}
}
执行结果: