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关系映射之一对多和多对一

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

  • 相关阅读:
    laytpl模板——怎么使用ajax与数据交互
    项目中遇到的几个日期转换的场景
    input可以自动换行吗???
    EL表达式 if 和 if else语句的写法
    小程序开发之背景图片的设置
    主流浏览器内核
    HTTP状态码
    (四)js数组方法一
    (效果二)js实现两个变量值的交换
    (十八)js控制台方法
  • 原文地址:https://www.cnblogs.com/zhouguanglin/p/7646255.html
Copyright © 2011-2022 走看看