Mybites的resultMap用法

112 阅读1分钟

resultMap解决问一个Java对象中,属性和数据库列名字不同的问题

**在这里插入图片描述

<!--    查询结果的映射-->
    <resultMap id="beanTotable" type="com.zks.vo.Emp">
        <result property="empname" column="ename"></result>
    </resultMap>
<!--    查询结果-->
    <select id="selectAll" resultMap="beanTotable">
        select * from emp
    </select>

这里在Java bean中的属性是empname而在数据库中的列名是ename

public void selectAll(){
//获取数据库链接
SqlSession sqlSession=MyBatiesUtils.getSqlSession();
//获取数据
List emp=sqlSession.selectList(“com.zks.dao.EmpMapper.selectAll”);
emp.stream().forEach(System.out::println);
}

resultMap解决一对多问题,比如在查询dept(多)信息的时候,附带把对应的emp

在这里插入图片描述

(一)中的信息都查询出来。
第一步:如图,在多方的java代码中加入这个

第二步:写配置文件

<!--    配置一对多环境下的resultMap-->
    <resultMap id="onetomany" type="com.zks.vo.Dept" autoMapping="true">
<!--        配置主键-->
        <id property="deptno" column="deptno"></id>
<!--        配置多方,一配置多的时候关键词是collection-->
        <collection property="empList" javaType="list" ofType="com.zks.vo.Emp" autoMapping="true">
            <id property="empno" column="empno"></id>
            <!--下面的empname和ename不一样所以要配置-->
            <result property="empname" column="ename"></result>
<!--            <result property="comm" column="comn"></result>-->
        </collection>
    </resultMap>
  <!--    查询数据-->
    <select id="queryAll" resultMap="onetomany">
        select * from dept d join emp e using(deptno)
    </select>

第三步,写java代码
public void queryAll(){
//获取数据库链接
SqlSession sqlSession= MyBatiesUtils.getSqlSession();
//获取数据
List deptList=sqlSession.selectList(“com.zks.dao.DeptMapper.queryAll”);
for (Dept dept : deptList) {
System.out.println(dept.getDeptno()+"–"+dept.getDname()+"–"+dept.getLoc());
dept.getEmpList().stream().forEach(System.out::println);
}
sqlSession.close();

}

resultMap解决多对一的映射
在这里插入图片描述
第一步:在多方的javabean中加入一方的属性
在这里插入图片描述
第二步:

    <resultMap id="manytoone" type="com.zks.vo.Emp" extends="beanTotable" autoMapping="true">
<!--        关系配置多对一的配置时候的关键词是 association-->
        <association property="dept" javaType="com.zks.vo.Dept" autoMapping="true">
            <!--        配置主键-->
            <id property="deptno" column="deptno"></id>

        </association>
    </resultMap>
<!--    多对一-->
    <select id="queryAll" resultMap="manytoone" >
        select * from emp e join dept d using(deptno)
    </select>

第三步:
Java代码
/**
* 多对一
*/
public void queryAll(){
//获取数据库链接
SqlSession sqlSession=MyBatiesUtils.getSqlSession();
//获取数据
List emp=sqlSession.selectList(“com.zks.dao.EmpMapper.queryAll”);
emp.stream().forEach(System.out::println);
}