gpt4 book ai didi

java - 使用 OneToMany 映射时 Hibernate 中的连接列为 Null

转载 作者:行者123 更新时间:2023-12-02 11:07:40 25 4
gpt4 key购买 nike

当使用 onetomanymappedby 映射时,我在 uid 列中得到 null车辆表。

一个用户可以拥有许多车辆,因此使用OneToMany映射..

Vehicle 表应包含用户表 ID 的引用 ..

这里,当显示Vehicle表时,我在uid列下得到null。它应该包含用户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]: /image/YyhsN.png

最佳答案

将其添加到您的代码中

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

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

关于java - 使用 OneToMany 映射时 Hibernate 中的连接列为 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50832254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com