Mybatis实现一对多查询

需求和使用情况说明


object one :

  //基本属性

  private List<object two> list;

  //省略set and get方法

说明:

对象一和对象二在不同的表中,但是对象一的主键是对象二的外键,因此对象一和对象二的对应关系为:1:n

查询对象一的同时可以把对象二中的所有和对象一的关联的对象的信息查询出来

因此可以使用 Mybatis中的一对多查询,查询的sql语法牵涉到外连接

结合具体实例

我这里做了一个简单的介绍:(一个租户下(tenant)有多个相关的用户(user)情况)

创建对应的实体类, Tenant 对应数据库表为tenant   User对应数据库中表为user

1 public class Tenant{
2   private String id;
3   private String name;
4   private List<User> users;
5 //.........
6 }

public class User {
  private String id;
  private String name;
}

创建对应的mybatis的xml文件

首先:对应返回类型 resultMap

//租户对应返回ResultMap,定义为基础返回数据类型
<resultMap id="BaseResultMap" type="com.licunzhi.test.Tenant">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
</resultMap>

//扩展resultMap,能够接收返回的带有Users的map
<resultMap id="TenantMembersMap" type="com.licunzhi.domain.Tenant" extends="BaseResultMap">
        <!-- 使用collection将users实体类中字段属性嵌套进来 -->
        <collection property="members" ofType="com.trendytech.cs.domain.business.User" >
            <id column="members_id" property="id" jdbcType="VARCHAR"/>
            <result column="members_name" property="name" jdbcType="VARCHAR" />
        </collection>
 </resultMap>

编写查询的sql语句

<select id="selectMembers" resultMap="TenanUsersMap" parameterType="java.lang.String">
        select t.*,
        u.id as members_id, u.name as members_name
        from tenant t
        /*外连接-获取租户下成员*/
        LEFT OUTER JOIN user u on u.tenant_id = t.id
        where  t.id = #{id,jdbcType=VARCHAR}
    </select>

  

展示其中的部分代码,部门代码的完整类参考地址:https://github.com/licunzhi/MybatisOneToMany

个人简答总结,若有不足之处见谅

欢迎加入Java、C、C++交流群,群聊号码:589780530

猜你喜欢

转载自www.cnblogs.com/licunzhi/p/8997181.html