zoukankan      html  css  js  c++  java
  • Mybatis-技术专区-如何清晰的解决出现「多对一模型」和「一对多模型」的问题

    基础使用篇

    一对一

    association

    association通常用来映射一对一的关系,例如,有个类user,对应的实体类如下:

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Accessors(chain = true)
    public class Student {
        private int id;
        private String name;
        /**
         * 学生要关联一个老师
         */
        private Teacher teacher;
    }
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Accessors(chain = true)
    public class Teacher {
        private int id;
        private String name;
    }
    Dao层进行Mapper查询操作
    public interface TeacherMapper {
        Teacher getTeacher(@Param("tid") int id);
        Teacher getTeacher2(@Param("tid") int id);
    }
    Dao层进行Mapper.xml文件
     <resultMap id="StudentTeacher" type="com.sunreal.pojo.Student">
            <result column="id" property="id"></result>
            <result column="name" property="name"></result>
            <association property="teacher" column="id"  javaType="com.sunreal.pojo.Teacher" select="getTeacher"/>
        </resultMap>
        <select id="getStudent" resultMap="StudentTeacher">
            select *
            from student
        </select>
        <select id="getTeacher" resultType="com.sunreal.pojo.Teacher">
            select *
            from teacher
            where id = #{id}
        </select>
        <resultMap id="StudentTeacher2" type="com.sunreal.pojo.Student">
            <result column="sid" property="id"></result>
            <result column="sname" property="name"></result>
            <association property="teacher" javaType="com.sunreal.pojo.Teacher">
                <result property="name" column="tname"></result>
            </association>
        </resultMap>
        <select id="getStudent2" resultMap="StudentTeacher2">
            select s.id sid, s.name sname, t.name tname
            from student s,
                 teacher t
            where s.tid = t.id
        </select>

    assocication:可以指定联合的JavaBean对象

    • select:指定相关查询结果sqlid
    • property="role“:指定哪个属性是联合的对象
    • javaType:指定这个属性对象的类型
    • column="{javabean熟悉=数据库字段,Javabean属性=数据库字段}"
    <association property="role" javaType="com.queen.mybatis.bean.Role">
        <id column="role_id" property="id"/>
        <result column="roleName" property="roleName"/>
    </association>

    以上如果跨越命名空间的情况下:select:需要用namespace.selectId进行指定。

    https://www.cnblogs.com/liboware/p/15220433.html

    故乡明
  • 相关阅读:
    MVC4做网站后台:用户管理 ——用户组补充
    MVC4做网站后台:用户管理 ——用户组
    过去的一年,2013!
    MVC4做网站后台:模块管理1、修改模块信息
    MVC4做网站后台:栏目管理3、删除栏目与左侧列表菜单
    MVC4做网站后台:栏目管理2、修改栏目
    MVC4做网站后台:栏目管理1、添加栏目-续
    MVC4做网站后台:栏目管理1、添加栏目
    MVC4做网站六后台管理:6.2网站信息设置
    MVC4做网站六后台管理:6.1.4管理员列表、添加及删除
  • 原文地址:https://www.cnblogs.com/luweiweicode/p/15224366.html
Copyright © 2011-2022 走看看