मैंने इस प्रश्न का अनुसरण करने का प्रयास किया है और मैंने एनोटेशन का उपयोग करके 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, [email protected](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);
मेरी टीम.जावा :
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
}
टीम.एसक्यूएल
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();
...
आशा है कि यह भविष्य के पाठकों के लिए उपयोगी होगा।