2013-02-18 101 views
0

我有一個問題,即使我明確地設置它們,Hibernate重置實體的ID。休眠設置ID爲空

這裏是我的兩個實體:

@Entity 
@Table(name="game") 
public class Game implements Serializable { 

    private String token; 

    private Set<DealersCard> dealersCards; 

    @Id 
    @Size(min=36, max=36) 
    @Column(name="token") 
    public String getToken() { 
     return token; 
    } 

    public void setToken(String token) { 
     this.token = token; 
    } 


    @OneToMany(fetch=FetchType.EAGER, cascade={CascadeType.ALL}) 
    public Set<DealersCard> getDealersCards() { 
     return dealersCards; 
    } 

    public void setDealersCards(Set<DealersCard> dealersCards) { 
     this.dealersCards = dealersCards; 
    } 

} 

@Entity 
@Table(name="dealers_card") 
public class DealersCard implements Serializable { 

    private String token; 
    private int id; 

    public void setVisible(boolean visible) { 
     this.visible = visible; 
    } 

    @ManyToOne 
    @MapsId("token") 
    @JoinColumn(name="token", referencedColumnName="token") 
    public Game getGame() { 
     return game; 
    } 

    public void setGame(Game game) { 
     this.game = game; 
    } 

    @Id 
    @Size(min = 36, max = 36) 
    public String getToken() { 
     return token; 
    } 

    public void setToken(String token) { 
     this.token = token; 
    } 

    @Id 
    public int getId() { 
     return id; 
    } 

    public void setId(int id) { 
     this.id = id; 
    } 
} 

當我創建遊戲的實例,通過EntityManager的分配兩個DealersCard ::持久化對象在數據庫中創建正確我可以稍後檢索它們,但是如果我檢索Game的一個實例,請添加DealersCard的另一個實例,並嘗試使用EntityManager :: merge,Hibernate更新數據庫,出於某種原因將token字段設置爲null,並將id設置爲0,我得到

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: ERROR: null value in column "token" violates not-null constraint Detail: Failing row contains (null, 0).

我試過MySQL和PostgreSQL,但我仍然遇到同樣的錯誤。我正在運行Glassfish 3.1.2.2,Hibernate Entity Manager 4.1.2,Java EE 6.

任何幫助表示讚賞。

謝謝!

回答

3

我不相信你的映射是非常正確的。你或許應該有:

@OneToMany(fetch=FetchType.EAGER, cascade={CascadeType.ALL}, mappedBy = "game") 
private Set<DealersCard> 

,並在許多方面:

@ManyToOne 
@JoinColumn(name="token") 
private Game game; 

然後從許多方面令牌屬性,只是有一個整數,它是你的@Id。

確保當您將新的DealerCards添加到您的設置中時,您可以在每個設置上設置遊戲並將其添加到集合中。

+0

你是完全正確的 - 問題是映射。謝謝! – Martynas 2013-02-19 00:04:39