本文介紹了MyBatis中的一對(duì)多關(guān)系的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我正在嘗試使用MyBatis在我的數(shù)據(jù)模型中映射一對(duì)多關(guān)系。這基于以下類:
class Team{
String mId;
String mName;
List<Player> mPlayers;
}
class Player{
String mId;
String mName;
}
我想編寫一個(gè)返回匹配列表的查詢,每個(gè)匹配列表都填充了與該匹配對(duì)應(yīng)的標(biāo)記。
<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>
但我遇到的問(wèn)題是,每個(gè)Team對(duì)象只填充了一個(gè)球員。如何更改此設(shè)置以確保每支球隊(duì)都包含屬于它的所有球員?
推薦答案
我試圖回答這個(gè)問(wèn)題,并使用注釋在Mybatis中創(chuàng)建了一對(duì)多關(guān)系。以下是我的代碼
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();
...
希望本文對(duì)未來(lái)的讀者有所幫助。
這篇關(guān)于MyBatis中的一對(duì)多關(guān)系的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,