简体   繁体   English

无法在休眠中创建一对多映射表

[英]Unable to create One to many mapping table in hibernate

I am quite new to hibernate. 我很冬眠。 I have created two entities like user and vehicle with user having one to many relationship with vehicle. 我创建了两个实体,例如用户和车辆,其中用户与车辆具有一对多的关系。

@OneToMany
@JoinColumn(name="Vehicle_id")
Collection<Vehicle> vehicle = new ArrayList<>();

and adding them to table like this 并像这样将它们添加到表中

UserInfo user = new UserInfo();
user.setUsername(username);
user.setPassword(password);
user.setDob(dob);

Vehicle vehicle = new Vehicle();
vehicle.setVehicleName("AUdi");
user.getVehicle().add(vehicle);

Vehicle vehicle2 = new Vehicle();
vehicle2.setVehicleName("BMW");
user.getVehicle().add(vehicle2);

SessionFactory sessionfactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(user);
session.save(vehicle);
session.save(vehicle2);
session.getTransaction().commit();
session.close();

But I am getting result like 但是我得到的结果像

Hibernate: insert into UserInformation (user_name, DOB) values (?, ?)
Hibernate: insert into Vehicle (vehicleName) values (?)
Hibernate: insert into Vehicle (vehicleName) values (?)
Hibernate: update Vehicle set Vehicle_id=? where vehicleID=?
Hibernate: update Vehicle set Vehicle_id=? where vehicleID=?

There is no table created like 没有创建像

insert into User_vehicle(User_id,vehicle_id) Values (?,?)

So I am not getting any table name User_vehicle in db. 所以我在db中没有得到任何表名User_vehicle

Hope you understand my question. 希望你理解我的问题。

You have specified @JoinColumn for a @OneToMany association, thus there will be a foreign key column on the many side. 您已指定@JoinColumn@OneToMany关联,因而会有在许多侧的外键列。 That is the recommended approach actually. 实际上,这是推荐的方法。

If you need to use join table for @OneToMany association, then you need to omit @JoinColumn and optionally specify @JoinTable to override the default names for the table and columns: 如果需要将@OneToMany表用于@OneToMany关联,则需要省略@JoinColumn并有选择地指定@JoinTable来覆盖表和列的默认名称:

@OneToMany
@JoinTable(
    name="User_Vehicle",
    joinColumns = @JoinColumn(name = "User_Id"),
    inverseJoinColumns = @JoinColumn(name = "Vehicle_Id")
)
Collection<Vehicle> vehicles = new ArrayList<>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM