1. 程式人生 > >Hibernate annotation多對多中間表設為新類後id無法成為主鍵的解決方案

Hibernate annotation多對多中間表設為新類後id無法成為主鍵的解決方案

問題背景:

眾所周知,在hibernate annotation 多對多對映中,若中間表有其他欄位,例如學生(T_Student)和課程(T_Course)之間的多對多關係,中間表Score(分數),學生表和課程表是多對多關係,另外為他們的關係新增額外的欄位---分數。

問題描述:

在馬士兵老師hibernate的視訊中,hibernateSchemaExport自動生成的表示以studentteacher表的id為主鍵的,score表的自動生成id無效,老師通過手動建表,然後插入資料。

解決方案:

只需要把在score類中的@id放在@ ManyToOne之前就可解決,可能是當hibernate

生成id時是根據score類的註解從上到下依次解析,到@id後就會生成主鍵,然後再到@ManyToOne,就不會再生成新的id了。

@Entity

public class Score {

       privateint id;

       privateint score;

       privateUser user;

       privateTeam team;

       @Id

       @GeneratedValue

       publicint getId() {

              returnid;

       }

       publicvoid setId(int id) {

              this.id= id;

       }

       publicint getScore() {

              returnscore;

       }

       publicvoid setScore(int score) {

              this.score= score;

       }

       @ManyToOne(cascade=CascadeType.ALL)

       @JoinColumn(name="user_id")

       publicUser getUser() {

              returnuser;

       }

       publicvoid setUser(User user) {

              this.user= user;

       }

       @ManyToOne(cascade=CascadeType.ALL)

       @JoinColumn(name="team_id")

       publicTeam getTeam() {

              returnteam;

       }

       publicvoid setTeam(Team team) {

              this.team= team;

       }

}