简体   繁体   中英

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.

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. 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
@JoinTable(
    name="User_Vehicle",
    joinColumns = @JoinColumn(name = "User_Id"),
    inverseJoinColumns = @JoinColumn(name = "Vehicle_Id")
)
Collection<Vehicle> vehicles = new ArrayList<>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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