我最近开始研究Hibernate并正在使用映射。在我的场景中,我有一个可以拥有多辆车的用户。在进行双向映射时,在第二个表中生成的列因为如果这个双向映射,我得到空值。我试过调试但没用。
UserDetails.java
package org.hibernate.OneToMany;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table (name = "USER_DETAILS")
public class UserDetails {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "USER_ID")
private int userId;
@Column(name = "USER_NAME")
private String userName;
@OneToMany(mappedBy="user")
private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();
public Collection<Vehicle> getVehicle() {
return vehicle;
}
public void setVehicle(Collection<Vehicle> vehicle) {
this.vehicle = vehicle;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Vehicle.java
package org.hibernate.OneToMany;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Vehicle {
@Id
@GeneratedValue
private int vehicleId;
private String vehicleName;
@ManyToOne
@JoinColumn(name ="USER_ID")
private UserDetails user;
public UserDetails getUser() {
return user;
}
public void setUser(UserDetails user) {
this.user = user;
}
public int getVehicleId() {
return vehicleId;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
}
HibernateTestOneToMany.java
package org.hibernate.OneToMany;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateTestOneToMany {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserName("First User");
Vehicle vehicle = new Vehicle();
vehicle.setVehicleName("Audi");
Vehicle vehicle2 = new Vehicle();
vehicle2.setVehicleName("Jeep");
user.getVehicle().add(vehicle);
user.getVehicle().add(vehicle2);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.save(vehicle);
session.save(vehicle2);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
输出:
此外,我发现有点难以理解为什么我们应该更喜欢双向到单向映射。
答案 0 :(得分:2)
您必须在要在测试中实例化的Vehicle对象内设置用户。