gpt4 book ai didi

java - Hibernate mappedBy 和@JoinColumn

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:17 26 4
gpt4 key购买 nike

当我尝试获得一对多和多对一关系时,车辆表上的连接列出现问题。为什么 hibernate 正在搜索列 USER_ID 而不是将其连接到表中?我知道加入的目的,但是当我尝试将它与映射的 By 属性一起使用时,我得到了这个错误。该代码有什么问题?

我得到的异常:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'USER_ID' in 'field list'

用户表:

@Entity
@Table(name = "users")
public class User {

public User(){}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getFirst_name() {
return first_name;
}

public void setFirst_name(String first_name) {
this.first_name = first_name;
}

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
this.salary = salary;
}

public String getLast_name() {
return last_name;
}

public void setLast_name(String last_name) {
this.last_name = last_name;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", first_name='" + first_name + '\'' +
", salary=" + salary +
", last_name=" + last_name +
'}';
}

public Collection<Vehicle> getVehicles() {
return vehicles;
}

public void setVehicles(Collection<Vehicle> vehicles) {
this.vehicles = vehicles;
}

@OneToMany(mappedBy = "user")
private Collection<Vehicle> vehicles = new ArrayList<>();

public Collection<Address> getAddresses() {
return addresses;
}
public void setAddresses(Collection<Address> addresses) {
this.addresses = addresses;
}

@ElementCollection // for saving the collection or persist it to database
@JoinTable(joinColumns = @JoinColumn(name = "fk_user_id")) // will add to the fk created table renamed column "fk_user_id"
private Collection<Address> addresses = new ArrayList<>();

@Id
@Column(name = "user_id")
private int id;
@Column(name = "first_name")
private String first_name;
@Column(name = "salary")
private int salary;
@Column(name = "last_name")
private String last_name;
}

车辆:

@Entity
@Table(name = "vehicle")
public class Vehicle {

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

@ManyToOne
@JoinColumn(name = "USER_ID")
private User user;

public int getVehicle_id() {
return vehicle_id;
}

public void setVehicle_id(int vehicle_id) {
this.vehicle_id = vehicle_id;
}

public String getVehicle_name() {
return vehicle_name;
}

public void setVehicle_name(String vehicle_name) {
this.vehicle_name = vehicle_name;
}

@Id
private int vehicle_id;
private String vehicle_name;

}

最佳答案

你对待 @JoinColumn 的方式与你想象的有点不同。

当你有配置时:

public class Vehicle {

@ManyToOne
@JoinColumn(name = "USER_ID")
private User user;

VEHICLEUSERS 表连接时,它告诉持久性提供程序使用 VEHICLE.USER_ID 列。

默认情况下,在 USERS 表端,使用主键,在本例中是具有相同名称的列:USERS.USER_ID(除非您指定在 @JoinColumn 中显式 referencedColumnName 属性)。

最重要的是,您的 VEHICLE 表中需要有一个 user_id 列。

关于java - Hibernate mappedBy 和@JoinColumn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42365989/

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