gpt4 book ai didi

java - MyBatis 中的一对多关系

转载 作者:可可西里 更新时间:2023-11-01 07:14:39 26 4
gpt4 key购买 nike

我正在尝试使用 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。我如何更改此设置以确保每个团队都包含属于它的所有球员?

最佳答案

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

希望这对 future 的读者有用。

关于java - MyBatis 中的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33151873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com