Hibernate和复合键

时间:2011-06-08 17:40:43

标签: java hibernate jpa

我正在使用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 (?, ?, ?, ?)

我不明白为什么。我在映射类中错了什么吗?

3 个答案:

答案 0 :(得分:3)

我在Coposite Key上遇到了同样的问题,并解决了在外部PK复制实体的get方法中的@JoinColumn hibernate注释中添加这个参数:

@JoinColumn(... ,updatable = false,insertable = false

答案 1 :(得分:1)

Hibernate确实希望你为每个表都有一个唯一的身份密钥;没有它就有“问题”。尝试在桌面上放一个身份密钥。

答案 2 :(得分:0)

您收到错误是因为您指定了两次座位。将其作为实体的属性PassengersOnTheFlight并将其作为密钥中的第二次。如果它是您的密钥的一部分,请将其从主对象中删除。如果它是一个整数,你可能不希望@JoinColumn为它。