MyBatis中的一对多关系

时间:2015-10-15 14:57:06

标签: java mysql mybatis

我正在尝试使用MyBatis在我的数据模型中映射一对多的关系。这基于以下类:

class Team{
    String mId;
    String mName;
    List<Player> mPlayers;
}

class Player{
    String mId;
    String mName;
}

我想编写一个返回匹配列表的查询,每个匹配都填充了与该匹配对应的标记。

<select id="getTeams" resultType="Team" resultMap="TeamMap">
    SELECT id, name, players.id as player_id, players.name as player_name
    FROM teams
    JOIN players ON teams.id = players.team_id
</select>


<resultMap type="Team" id="TeamMap">
    <id property="mId" column="id"/>
    <result property="mName" column="name"/>

    <collection property="mTags" javaType="List" ofType="Player">
        <id property="player_id" column="mId"/>
        <result property="player_name" column="mName"/>
    </collection>

</resultMap>

但我遇到的问题是每个Team对象只填充一个Player。如何更改此项以确保每个团队都包含属于它的所有玩家?

2 个答案:

答案 0 :(得分:7)

我试图关注这个问题,并且我使用Annotations在Mybatis中创建了一对多关系。以下是我的代码,

<强> UserMapper.java

@Select("SELECT teamId, name FROM TEAM")
    @Results(value = {
        @Result(property="teamId", column = "teamId"),
        @Result(property="name", column = "name"),
        @Result(property="players", column="teamId", javaType= List.class, many=@Many(select="selectPlayers"))
    })   
public List<Team> getAllTeams();

@Select("SELECT * FROM PLAYER WHERE teamId = #{teamId}")
    @Results(value={
        @Result(property="playerId", column ="playerId" ),
        @Result(property="name", column = "name")
    })
List<Player> selectPlayers(String teamId);

我的 Team.java

public class Team {

    private Long teamId;
    private String name;
    private List<Player> players;

    //...getters and setters

}

<强> Player.java

public class Player {

    private Long playerId;
    private String name;
    private Team team;

    //...getter and setters

}

<强> team.sql

CREATE TABLE `team` (
  `teamId` bigint(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`teamId`)
)

<强> player.sql

CREATE TABLE `player` (
  `playerId` bigint(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `teamId` bigint(10) DEFAULT NULL,
  PRIMARY KEY (`playerId`),
  KEY `FK_TEAM_ID` (`teamId`),
  CONSTRAINT `FK_TEAM_ID` FOREIGN KEY (`teamId`) REFERENCES `team` (`teamId`)
)

<强> UserServiceImpl.java

@Autowired
private UserMapper userMapper;

...
/* Get the list of teams with players data */
List<Team> teams = userMapper.getAllTeams();
...

希望这对未来的读者有用。

答案 1 :(得分:2)

找到解决方案。我所要做的就是从#34; id&#34;更改集合中的player_id映射。到&#34;结果&#34;。