Mybatis实现多表联查

绝地灬酷狼 2022-02-03 14:57 398阅读 0赞

一、Mybatis实现多表联查询

1、Mybatis实现多表联查询方式

  • 业务装配对两个表写单独的sql语句,在业务(service)把查询结果进行联合。
  • 使用Auto Mapping特性,在实现两个表联合查询时通过别名完成自动映射。
  • 使用Mybatis的标签进行实现

2、多表查询时类中包含另一个对象的分类

  • 单个对象
  • 集合对象

二、resultMap标签

1、标签单表中的映射

写在
select * from student where tid = #{0}

  • 在TeacherMapper.xml中添加查询全部,然后通过来装配其它的,代码:








  • 还是和查询单个对象一样这里中使用来匹配集合,其中property还是类中的属性名,select是要执行的sql语句,column为要传递的参数字段。

    5、使用实现加载集合数据(联合查询方式)

    只需要写一条SQL,在TeacherMapper.xml中完成,对于老师的属性在中直接用进行装配(将字段别名与属性匹配),对于Student对象集合用标签来映射,其中 property还是代表在类中该对象集合属性的名称 另外要设置ofType表示返回集合的泛型,其它的还一次对应匹配即可。具体代码实例:

    1. <!-- 使用联合查询 -->
    2. <resultMap type="Teacher" id="teacMap1">
    3. <id column="tid" property="id"/>
    4. <result column="tname" property="name"/>
    5. <collection property="list" ofType="Student">
    6. <id column="sid" property="id"/>
    7. <result column="sname" property="name"/>
    8. <result column="age" property="age"/>
    9. <result column="tid1" property="tid"/>
    10. </collection>
    11. </resultMap>
    12. <select id="selAll1" resultMap="teacMap1">
    13. select t.id tid, t.name tname, s.id sid, s.name sname,age ,s.tid tid1
    14. from teacher t left join student s on t.id = s.tid
    15. </select>

    三、使用Auto Mapping结合别名实现多表查询

    • 只能使用多表联合查询方式.
    • 要求:查询出的列别和属性名相同.
    • 实现方式,在 SQL 是关键字符,两侧添加反单引号
    • 只能适用于单个对象

    代码实例:

    1. <select id="selAll" resultType="student">
    2. select t.id `teacher.id`,t.name `teacher.name`,s.id id,s.name name,age,tid
    3. from student s LEFT JOIN teacher t on t.id=s.tid
    4. </select>

    四、Mybatis注解

    • 注解:为了简化配置文件.
    • Mybatis 的注解简化 mapper.xml 文件.
    • 如果涉及动态 SQL 依然使用 mapper.xml
    • mapper.xml 和注解可以共存.
    • 使用注解时 mybatis.xml 中使用

    一般实例:

    • 实现查询:

      @Select(“select * from teacher”)
      List selAll();

    • 实现新增

      @Insert(“insert into teacher values(default,#{name})”)
      int insTeacher(Teacher teacher);

    将主键带回来的方式:设置@Options注解并配置(useGeneratedKeys=true,keyProperty=”id”)

    1. @Insert("insert into log values(default,#{accOut},#{accIn},#{money})")
    2. @Options(useGeneratedKeys=true,keyProperty="id")
    3. int insLog(Log log);
    • 实现删除(主要看基本类型参数的取法)

      @Delete(“delete from teacher where id=#{0}”)
      int delById(int id);

    发表评论

    表情:
    评论列表 (有 0 条评论,398人围观)

    还没有评论,来说两句吧...

    相关阅读

      相关 mybatis如何写联查

      诸法无我,多表联查的实现可以使用 MyBatis 的 XML Mapper 或注解的方式。在 XML Mapper 中,可以使用 <select> 元素来描述多表联查的语句。其