Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Hubungan satu ke banyak di MyBatis

Saya sudah mencoba mengikuti pertanyaan ini dan saya telah membuat hubungan Satu-ke-Banyak di Mybatis menggunakan Anotasi. Berikut adalah kode saya,

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);

Team.java saya :

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();
...

Semoga ini bermanfaat bagi pembaca di masa mendatang.



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. loop hasil mysql di php di luar permintaan mysql

  2. MYSQL pilih sepotong string dan pesan berdasarkan potongan itu

  3. Praktik terbaik dengan data historis di database MySQL

  4. Mengonversi kode MySQL ke Access:GROUP_CONCAT dan triple JOIN

  5. Bagaimana cara mengubah Collation Kolom tanpa kehilangan atau mengubah data?