使用OneToMany映射时,在Hibernate中的Join Column中获取Null

时间:2018-06-13 08:14:27

标签: java hibernate hql hibernate-mapping

onetomany使用mappedby映射后,我nulluidvehicle列中获取User

一个vehicle可以有多个OneToMany s Vehicle映射使用..

user table id表应包含null ..

的引用

在显示uid表时,我在Vehicle列下获取user id。它应包含mappedby的值。没有 @Entity @Table(name="User_Details") public class UserDetails { private long uid; @Column(name="fname") private String name; private Set<Vehicle> vehicle=new HashSet<Vehicle>(); public UserDetails() { } public UserDetails(String name) { this.name = name; } @Id @Column(name="uid") @GeneratedValue public long getUid() { return uid; } public void setUid(long uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(mappedBy="user",cascade = CascadeType.ALL) public Set<Vehicle> getVehicle() { return vehicle; } public void setVehicle(Set<Vehicle> vehicle) { this.vehicle = vehicle; } } @Entity @Table(name="Vehicle") public class Vehicle { private long id; @Column(name="vname") private String name; private UserDetails user; public Vehicle() { } public Vehicle(String name, UserDetails user) { super(); this.name = name; this.user = user; } @Id @Column(name="vid") @GeneratedValue public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne @JoinColumn(name = "uid") **References UserDetails table** public UserDetails getUser() { return user; } public void setUser(UserDetails user) { this.user = user; } } public class App { public static void main(String\[\] args) { SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory(); Session session=sessionFactory.openSession(); session.beginTransaction(); UserDetails user=new UserDetails(); user.setName("Rohit"); Vehicle vehicle1=new Vehicle(); vehicle1.setName("Hyundai1"); Vehicle vehicle2=new Vehicle(); vehicle2.setName("Maruti1"); Set<Vehicle> set = new HashSet<Vehicle>(); set.add(vehicle1); set.add(vehicle2); user.setVehicle(set); session.save(user); session.getTransaction().commit(); session.close(); }**][1]][1] [1]: https://i.stack.imgur.com/YyhsN.png ,它运行正常。

"status=1"

1 个答案:

答案 0 :(得分:1)

将此添加到您的代码中

vehicle1.setUser(user)
vehicle2.setUser(user)

您没有设置关系的拥有方(车辆 - >用户)。