美文网首页
mybatis一对多

mybatis一对多

作者: 粑粑八成 | 来源:发表于2020-02-22 10:46 被阅读0次

情景:一个用户有多个账户
需求:查询账户及其关联的用户信息
实现:
1、自己另外封装个实体类(不常用)
2、使用resultMap 和 association

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.lernamybatis.repository.IAccountDAO">

  <resultMap id="accountUserMap" type="com.example.lernamybatis.entity.Account">
    <id property="id" column="aid"></id>
    <result property="uid" column="uid"></result>
    <result property="money" column="money"></result>
    <association property="user" column="uid">
      <id property="id" column="id"></id>
      <result column="username" property="userName"></result>
      <result column="address" property="address"></result>
      <result column="sex" property="sex"></result>
      <result column="birthday" property="birthday"></result>
    </association>
  </resultMap>

  <select id="findAll" resultMap="accountUserMap">
        select u.*,a.id as aid,a.uid,a.money from account a ,user u where u.id = a.uid
  </select>

  <select id="findAllAccount" resultType="com.example.lernamybatis.entity.AccountUser">
    select a.*, u.username,u.address from account a, user u where a.uid=u.id;
  </select>
</mapper>

需求:查询所有用户及其拥有的账户
实现:使用collection标签,对应列名和实体字段名

 <resultMap id="userAccountMap" type="com.example.lernamybatis.entity.User">
    <id property="id" column="id"></id>
    <result property="userName" column="username"></result>
    <result property="sex" column="sex"></result>
    <result property="address" column="address"></result>
    <result property="birthday" column="birthday"></result>
    <collection property="accounts" ofType="com.example.lernamybatis.entity.Account">
      <id property="id" column="aid"></id>
      <result property="uid" column="uid"></result>
      <result property="money" column="money"></result>
    </collection>
  </resultMap>

  <select id="selectAll" resultMap="userAccountMap">
        select u.*, a.id as aid, a.uid, a.money from user u left join account a on u.id = a.uid
  </select>

相关文章

  • mybatis

    mybatis 高级映射 一对一 一对多 mybatis generator 的使用 多个条件 or 连接查询 但...

  • Mybatis 知识

    基础 一对一 多对一 一对多 多对多 association vs collection Mybatis...

  • mybatis一对多

    情景:一个用户有多个账户需求:查询账户及其关联的用户信息实现:1、自己另外封装个实体类(不常用)2、使用resul...

  • mybatis 一对多

    积土成山,风雨兴焉 需求:分页查询TbPoint(一的一方),且将它下面的List (多的一方)也一...

  • Mybatis-一对多

    代码

  • mybatis一对多配置

    第一种方式: supplier_id一般为主表的标识,附表引用,用来聚合数据,此外id行的column不能一样,否...

  • mybatis一对多查询

    association联合,是一对一查询

  • 【Mybatis】一对多查询

    如果有顺序要求,千万不要用set 与Phoenix不同,在mysql中查询的结果不会按照id默认排序。所以如果页面...

  • 7. MyBatis 多表查询

    实现Role 到User 多对多,使用Mybatis 实现一对多关系的维护。多对多关系其实我们看成是双向的一对多关...

  • 09|第九课:一对一以及一对多关联查询详解

    一、历史回顾 (一)、关联查询 1、大多框架都分别讲解 一对一 一对多 多对一 多对多 2、Mybatis只有两种...

网友评论

      本文标题:mybatis一对多

      本文链接:https://www.haomeiwen.com/subject/tpakqhtx.html