• 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 || 点返回首页

  • 相关阅读:
    Oracle中查看所有表和字段以及表注释.字段注释
    利用Excel表格中的宏,轻松提取首字母
    IntelliJ IDEA 14 注册码
    oracle initialization or shutdown in progress解决方法
    IIS6.0 IIS7.5应用程序池自动停止的解决方法
    Yii1.1测试环境配置(一)
    流行界面库
    delphi image控件上画矩形的问题
    delphi中TQueue的使用问题
    ShellExecute函数的问题
  • 原文地址:https://www.cnblogs.com/aeon/p/9758255.html
Copyright © 2020-2023  润新知