我是Hibernate的新手,我正在尝试在Person和Vehicle类之间建立OneToMany / ManyToOne双向关系。在我的例子中,一个人可以有很多车辆而一辆车只属于一个人。我需要一个连接表:PERSON_VEHICLE,PERSON_ID和VEHICLE_ID作为列,VEHICLE表中有PERSON_ID列。这是我的班级设计:
人员类:
@Entity
public class Person {
@Id
@GeneratedValue
@Column(name = "PERSON_ID")
private int id;
private String name;
@OneToMany(cascade=CascadeType.ALL, mappedBy="person")
private Collection<Vehicle> vehicleList = new ArrayList<>();
车辆类:
@Entity
public class Vehicle {
@Id
@GeneratedValue
@Column(name = "VEHICLE_ID")
private int id;
private String name;
@ManyToOne
@JoinColumn(name="PERSON_ID")
@JoinTable(name="PERSON_VEHICLE", joinColumns=@JoinColumn(name="VEHICLE_ID"),
inverseJoinColumns=@JoinColumn(name="PERSON_ID"))
private Person person;
以下是Hibernate生成的DDL。
create table Person (
PERSON_ID integer not null auto_increment,
name varchar(255),
primary key (PERSON_ID)
)
create table Vehicle (
VEHICLE_ID integer not null auto_increment,
name varchar(255),
primary key (VEHICLE_ID)
)
create table PERSON_VEHICLE (
PERSON_ID integer,
VEHICLE_ID integer not null,
primary key (VEHICLE_ID)
)
alter table PERSON_VEHICLE
add index FK_h3d046x5uvbo53p8ms41hwqx (PERSON_ID),
add constraint FK_h3d046x5uvbo53p8ms41hwqx
foreign key (PERSON_ID)
references Person (PERSON_ID)
alter table PERSON_VEHICLE
add index FK_mtm2mn29hel3lbpl6i526w40v (VEHICLE_ID),
add constraint FK_mtm2mn29hel3lbpl6i526w40v
foreign key (VEHICLE_ID)
references Vehicle (VEHICLE_ID)
VEHICLE表没有PERSON_ID列。出了点问题,但我找不到问题所在。