zoukankan      html  css  js  c++  java
  • MyBatis 关系映射XML配置

    关系映射


    在我看来这些实体类就没啥太大关联关系,不就是一个sql语句解决的问题,直接多表查询就完事,程序将它设置关联就好

    xml里面配置也是配置了sql语句,下面给出几个关系的小毛驴(xml)

    一对多


    <mapper namespace="com.entity.UserMapper">
    <!--一对多关联查询  -->
    <resultMap id="user_info" type="com.entity.User">
      <result property="id" column="id" />
      <result property="username" column="username"/>
      <result property="password" column="password"/>
      <collection property="userInfos" ofType="com.entity.UserInfo" column="uid">
              <result property="id" column="id"/>
              <result property="address" column="address"/>
      </collection>
    </resultMap>
      <select id="getUser"  resultMap="user_info">
        select * from user u,userinfo i where u.id=i.uid and u.id=#{id}
      </select>
    </mapper>

    实体类,给出字段,自己get和set

    /**
     * 
     * @author 坚持到你GL
     *
     */
    public class User {
        private int id;
        private String username;
        private String password;
        private List<UserInfo> userInfos;
        
    /**
     * 
     * @author 坚持到你GL
     *
     */
    public class UserInfo {
        private int id;
        private String address;
        private int uid;

    多对多


    <mapper namespace="com.entity.UserMapper">
    <!--多对多  -->
    <resultMap id="ug" type="com.entity.User">
      <result property="id" column="id" />
      <result property="username" column="username"/>
      <result property="password" column="password"/>
      <collection property="groups" ofType="com.entity.Group">
              <id property="id" column="gid"/>
              <result property="info" column="info"/>
      </collection>
    </resultMap>
      <select id="getUserGroup"  resultMap="ug">
        select * from user u,    `group` g,user_group ug where g.id=#{id} and u.id=ug.uid and g.id=ug.gid
      </select>
      </mapper>

    实体类

    /**
     * 
     * @author 坚持到你GL
     *
     */
    public class User {
        private int id;
        private String username;
        private String password;
        private List<Group> groups;
    /**
     * 
     * @author 坚持到你GL
     *
     */
    public class Group {
        private int id;
        private String info;
        private List<User>users;
    /**
     * 中间表
     * @author 坚持到你GL
     *
     */
    public class UserGroup {
        private int id;
        private int uid;
        private int gid;

    一对一


    关键在于

    <collection property="groups" ofType="com.entity.Group">将ofType变成javaType
    推荐个网址

    mybatis关系映射之一对多和多对一

       【版本声明】本文为博主原创文章,转载请注明出处

  • 相关阅读:
    SVN服务器搭建和使用
    oracle 存储过程
    PLSQL函数
    PL/SQL --> 游标
    PL SQL 游标学习
    PLSQL存储过程
    利用jqueryRotare实现抽奖转盘
    NSString 与NSMutableString的区别
    第一章 熟悉Objective -C 编写高质量iOS与OS X代码的52 个有效方法
    第8章 应用协议 图解TCP/IP 详解
  • 原文地址:https://www.cnblogs.com/zhouguanglin/p/7646255.html
Copyright © 2011-2022 走看看