MyBatis-如何从同一表中联接多个列

时间:2019-06-27 11:07:29

标签: spring mybatis spring-mybatis

我正在尝试学习如何针对给定的ID将一个表中的多个列连接到另一个表中的单个列。

这是我的团队表:

create table teams ( 
  id varchar(10),
  name varchar(30),
  primary key (id)
);

这是我的球队比赛表:

create table teammatch (
  id integer,
  firstTeamId varchar,
  secondTeamId varchar,
  matchId integer,
  primary key(id),
  foreign key (firstTeamId) references teams (id),
  foreign key (secondTeamId) references teams (id)
);

我的SQL:

select teammatch.*, t1.*, t2.*
    from teammatch
    inner join teams t1 on teammatch.firstTeamId = t1.id
    inner join teams t2 on teammatch.secondTeamId = t2.id
    where teammatch.id = #{id}

数据:

ID      FIRSTTEAMID     SECONDTEAMID 
1       POR             DEN 
2       TOR             PHI 

此查询返回t1和t2的POR小组,但我需要 为t1返回POR,为t2返回DEN

编辑: 当我在H2数据库中编写sql查询时,此方法工作正常,但当我在xml映射器文件中使用mybatis编写该查询时,它为两个字段返回相同的值。

这是我的ResultMap

<resultMap id="TeamMatchMap" type="TeamMatch">
    <id column="id" property="id" />

    <association property="firstTeamId" column="firstTeamId" javaType="Team">
      <id column="id" property="id" />
      <result column="name" property="name" />
    </association>

    <association property="secondTeamId" column="secondTeamId" javaType="Team">
      <id column="id" property="id" />
      <result column="name" property="name" />
    </association>
  </resultMap>

1 个答案:

答案 0 :(得分:1)

请尝试将您的映射器更改为类似的内容

<?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>
    <select id="getTeammatches"
            resultMap="teamMatchMap">
        select
            teammatch.id as matchid       ,
            t1.id        as firstteam_id  ,
            t1.name      as firstteam_name,
            t2.id        as secondteam_id ,
            t2.name      as secondteam_name
          from teammatch
            inner join teams t1 on teammatch.firstTeamId = t1.id
            inner join teams t2 on teammatch.secondTeamId = t2.id
          where teammatch.id = #{id}
    </select>
    <resultMap type="TeamMatch" id="teamMatchMap">
        <result property="id" column="MATCHID"/>
        <association property="team1" columnPrefix="FIRSTTEAM_" resultMap="teamMap"/>
        <association property="team2" columnPrefix="SECONDTEAM_" resultMap="teamMap"/>
    </resultMap>
    <resultMap type="Team" id="teamMap">
        <result property="id" column="ID"/>
        <result property="name" column="NAME"/>
    </resultMap>
</mapper>

通过为resultMap声明单独的Team或引用现有的{p},您无需在association-tag的body-tag中映射列两次

您为column使用了association属性-据我所知,仅当您希望myBatis执行另一个select-tag

时才使用它

修改

我在阅读您的编辑和评论之前就写了映射器

如果您的Team类提供带有ID和名称的构造函数,那么您的teamMap也可以像这样

    <resultMap type="Team" id="teamMap">
        <constructor>
            <idArg column="ID"/>
            <arg column="NAME"/>
        </constructor>
    </resultMap>