在onetomany
使用mappedby
映射后,我null
在uid
个vehicle
列中获取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"
答案 0 :(得分:1)
将此添加到您的代码中
vehicle1.setUser(user)
vehicle2.setUser(user)
您没有设置关系的拥有方(车辆 - >用户)。