MyBatis中的一对多关系

2022-05-06 00:00:00 mysql java 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对象只填充了一个球员。如何更改此设置以确保每支球队都包含属于它的所有球员?


解决方案

我试图回答这个问题,并使用注释在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();
...

希望本文对未来的读者有所帮助。

相关文章