2011-06-08 144 views
1

我使用Hibernate和Oracle數據庫,只是卡住了。休眠和複合鍵

我試圖映射此表:

CREATE TABLE passengers_on_the_flight 
(
    flight_id NUMERIC(10) REFERENCES flight(flight_id), 
    passenger_id NUMERIC(20) REFERENCES passenger(passenger_id), 
    seat  NUMERIC(5) NOT NULL,   
    CONSTRAINT "not free" PRIMARY KEY (flight_id,passenger_id,seat) 
); 

所以我的映射類的樣子:

@Entity 
@Table(name = "PASSENGERS_ON_THE_FLIGHT") 
@NamedQueries({ 
@NamedQuery(name = "PassengersOnTheFlight.findAll", query = "SELECT p FROM PassengersOnTheFlight p")}) 
public class PassengersOnTheFlight implements Serializable { 

private static final long serialVersionUID = 1L; 


@EmbeddedId 
protected PassengersOnTheFlightPK passengersOnTheFlightPK; 
public PassengersOnTheFlightPK getPassengersOnTheFlightPK() { 
return passengersOnTheFlightPK; 
} 
public void setPassengersOnTheFlightPK(PassengersOnTheFlightPK passengersOnTheFlightPK) { 
this.passengersOnTheFlightPK = passengersOnTheFlightPK; 
} 

@JoinColumn(name = "SEAT", referencedColumnName = "SEAT", insertable = false, updatable = false) 
private int seat; 


@JoinColumn(name = "FLIGHT_ID", referencedColumnName = "FLIGHT_ID", insertable = false, updatable = false) 
@ManyToOne 
private Flight flight; 


@JoinColumn(name = "PASSENGER_ID",referencedColumnName = "PASSENGER_ID",insertable = false, updatable = false) 
@ManyToOne 
private Passenger passenger; 

//Getters, setters for seat, flight and passanger 

而且主鍵類:

@Embeddable 
public class PassengersOnTheFlightPK implements Serializable { 


@Column(name = "FLIGHT_ID",nullable=false) 
private long flightId; 


@Column(name = "SEAT",nullable=false) 
private int seat; 

@Column(name = "PASSENGER_ID", nullable=false) 
private Long passengerId; 

//Getters and setters for seat, flightId and passangerId 

我試着堅持東西,並得到

ORA-00957: duplicate column name 

這因爲Hibernate會這樣的查詢:

insert into PASSENGERS_ON_THE_FLIGHT (seat, FLIGHT_ID, PASSENGER_ID, SEAT) values (?, ?, ?, ?) 

我不知道爲什麼。我在映射類中錯過了什麼嗎?

+0

爲什麼主鍵的座位部分? passenger_id和flight_id應該足夠了。 雖然我確實同意Paul的觀點,但是在桌子上放置身份證是一個更好的設計。使事情變得更簡單。 – 2011-06-08 17:51:03

+0

此外,座位應該被標註爲@Column,而不是@JoinColumn – 2011-06-08 17:54:11

回答

1

Hibernate真的很想讓你爲每個表擁有一個唯一的標識鍵;它沒有它就有「問題」。嘗試在你的桌子上放一個身份證。

+0

他確實擁有嵌入式密鑰。我錯過了什麼嗎? – 2011-06-08 20:51:16

0

你得到你的錯誤,因爲你指定的座位兩次。一旦您將其作爲您的實體PassengersOnTheFlight的財產並在密鑰中第二次使用。如果它是您的鑰匙的一部分,請將其從主要對象中移除。如果它是一個整數,你可能不需要@JoinColumn

3

我得到了Coposite鍵同樣的問題,解決它添加此PARAMS在@JoinColumn外部PK重複實體get方法冬眠註釋:

@JoinColumn(... ,可更新= false,insertable = false