2011-08-04 63 views
1

鑑於這些實體:JPA - 表錯誤創建

class SportTeam { 
    @Id 
    @GeneratedValue 
    long id; 
    @OneToMany 
    private Set<PLayer> players; 
    @OneToMany 
    private Set<Player> stars; 
} 
// A sport team can have multiple players and some of those players can be stars. 

class Player { 
    @Id 
    @GeneratedValue 
    long id; 
    (...) 
} 

這裏產生由Hibernate的DDL:

CREATE TABLE sportteam 
(
    id bigint NOT NULL, 
    (...) 
    CONSTRAINT sportteam_pkey PRIMARY KEY (id) 
) 

CREATE TABLE sportteam_player 
(
    sportteam_id bigint NOT NULL, 
    player_id bigint NOT NULL, 
    star_id bigint NOT NULL, 
    CONSTRAINT sportteam_player_pkey PRIMARY KEY (sportteam_id, star_id), 
    CONSTRAINT fk6cf55c6645d973bc FOREIGN KEY (player_id) 
    REFERENCES player (id) MATCH SIMPLE 
    ON UPDATE NO ACTION ON DELETE NO ACTION, 
    CONSTRAINT fk6cf55c66ca1af8b8 FOREIGN KEY (star_id) 
    REFERENCES player (id) MATCH SIMPLE 
    ON UPDATE NO ACTION ON DELETE NO ACTION, 
    CONSTRAINT sportteam_player_star_id_key UNIQUE (star_id), 
    CONSTRAINT sportteam_player_player_id_key UNIQUE (player_id) 
)  


CREATE TABLE player 
(
    id bigint NOT NULL, 
    (...) 
    CONSTRAINT player_pkey PRIMARY KEY (id) 
) 

我寧願sportteam_player看起來是這樣的:

CREATE TABLE sportteam_player 
(
    sportteam_id bigint NOT NULL, 
    player_id bigint NOT NULL, 
    is_star boolean DEFAULT 'FALSE', 
    CONSTRAINT sportteam_player_pkey PRIMARY KEY (sportteam_id, player_id), 
    CONSTRAINT fk6cf55c6645d973bc FOREIGN KEY (player_id) 
    REFERENCES player (id) MATCH SIMPLE 
    ON UPDATE NO ACTION ON DELETE NO ACTION, 
    CONSTRAINT fk6cf55c66ca1af8b8 FOREIGN KEY (sportteam_id) 
    REFERENCES sportteam (id) MATCH SIMPLE 
    ON UPDATE NO ACTION ON DELETE NO ACTION 
)  

我能怎麼做 ?

+0

你打算是明星球員在球員被複制設定? – Jeremy

+0

是的。相同的Player類可以在兩個集合中(作爲玩家和作爲明星)。 – Stephan

+1

我發現這個鏈接可以幫助你:http://sieze.wordpress.com/2009/09/04/mapping-a-many-to-many-join-table-with-extra-column-using-jpa/ – Jeremy

回答

4

對JPA關係進行建模是不可行的。您認爲Team-to-Star是關係數據庫意義上的一對多關係。這當然是某種刻板印象的關係,但它是基於一個球員的特性,不管它是否是明星。所以:

class Player { 
    @Id 
    @GeneratedValue 
    long id; 
    @Column(name = 「is_star」, columnDefinition="boolean default false") 
    boolean star; 
    (...) 
} 

class SportTeam { 
    @Id 
    @GeneratedValue 
    long id; 
    @OneToMany 
    private Set<PLayer> players; 

    public Collection<Player> getStars() { 
    // return your stars here, filter through players. 
    // if you want you can do caching, but remember to set the field to @Transient 
    // so that Hibernate does not think, it could be a relation 
    } 
} 

爲什麼要這樣做?無論如何,在SportTeam中你已經加載了所有的球員。沒有理由通過數據庫來做到這一點。成爲明星是明星的財產,如果你需要SportTeam課程的名單,這對現有球員來說只是一種不同的觀點。

+0

也可以創建一個類'sportteam_player',它將映射到連接表。 – Stephan