• mybatis中表的关联


    一、数据库中表的关联有三种形式

      a)一对一

      b)一对多(多对一)

      c)多对多

    二、mybatis实现多对一(两种方式)、这里我们用用户和部门进行举例实现(多个用户(员工)同属于一个部门、一个部门有多个用户(员工))

      a)结果嵌套查询

      dao接口:  

    List<User> selectAllUsers();

      dao实现类:

    @Override
        public List<User> selectAllUsers() {
            SqlSession sqlSession=null;
            List<User> userList = null;
            try {
                userList = MyBatisUtils.getSqlSesion("mybatis/mybatis.xml").selectList("edu.aeon.mybatis.entity.UserMapper.selectAllUsers");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return userList;
        }

      实体类和数据库的sql映射文件:(User.Mapper.xml)

    <!-- ①多对一 :按结果嵌套-->
     <select id="selectAllUsers" resultMap="UserDepartment">
         select u.*,d.* from user u,department d where u.did = d.did
     </select>
     <resultMap type="User" id="UserDepartment">
         <id property="uid" column="uid"/>
         <result property="uname" column="uname"/>
         <result property="upw" column="upw"/>
         <association property="department" javaType="Department">
             <id property="did" column="did"/>
             <result property="dname" column="dname"/>
         </association>
     </resultMap>

      测试类:  

    public static void testSelectAllUsers(){
            UserDao userDao =new UserDaoImpl();
            List<User> userList = userDao.selectAllUsers();
            for(User user:userList){
                System.out.println(user);
            }
        }

      b)按查询嵌套

        dao及实现同上

        mybatis核心配置文件:

        

    <mappers>
     <!-- 引入实体类到数据库的sql映射文件 -->
     <mapper resource="edu/aeon/mybatis/entity/User.Mapper.xml"/>
     <mapper resource="edu/aeon/mybatis/entity/Deparment.Mapper.xml"/>
     </mappers>

        实体类和数据库的sql映射文件:(User.Mapper.xml)

     <!-- ②多对一 :按查询嵌套-->
     <select id="selectAllUsers" resultMap="UserDepartment">
         select * from user
     </select>
     <resultMap type="User" id="UserDepartment">
        <association property="department" column="did" javaType="Department" select="edu.aeon.mybatis.entity.DepartmentMapper.selectDepartmentById"></association>
     </resultMap>

        实体类和数据库的sql映射文件:(Deparment.Mapper.xml)

    <mapper namespace="edu.aeon.mybatis.entity.DepartmentMapper">
     <select id="selectDepartmentById" parameterType="int" resultType="Department">
         select * from department where did=#{did}
     </select>
    </mapper>

      测试同上!

      

        

    如有任何疑问可联系邮箱: 给我发邮件、或直接联系QQ:1584875179 || 点返回首页

  • 相关阅读:
    核心API的使用(给定一个字符串,统计每个字符出现的次数)
    将博客搬至CSDN
    [DEBUG] python写文件时print漏掉整行数据
    [DEBUG] pyinstaller打包-命令行报错 pyinstaller failed to execute script 脚本名
    [DEBUG] springboot结合freemaker和js实现页面跳转和传值-踩坑记录
    724. 寻找数组的中心索引
    1010. 总持续时间可被 60 整除的歌曲
    27.移除元素
    [tensorflow] 入门day1-数据整理与展示
    [tensorflow] 安装
  • 原文地址:https://www.cnblogs.com/aeon/p/9758255.html
Copyright © 2020-2023  润新知