我遇到了一個用戶類和汽車類的情況。 和我的mysql數據庫中的表可能看起來像這樣 下面是我如何想象這兩個實體之間的關係的草圖。如何正確構造兩個類之間的休眠關係
user user_car car
username firstname lastname <----> username car_id <----> car_id cartype
tea bruce anderson tea 1 1 ford123
t arnold mena tea 2 2 audio2
t 2
用戶有一個Set,其中包含汽車的對象。但汽車不應該引用任何用戶。我已經嘗試了幾種方法,但總是以「重複鍵」爲主的相同錯誤結束。
@Entity
public class car {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long car_id;
private String type;
public car(){
}
public long getCar_id() {
return car_id;
}
public void setCar_id(long car_id) {
this.car_id = car_id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
用戶類
@Entity
public class userr {
@Id
private String username;
private String firstname;
private String lastname;
//Some relation here, which I do not know how to properly set up
private Set<Car> cars = new HashSet<>();
public userr(){
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Set<Car> getCars() {
return cars;
}
public void setCars(Set<Car> cars) {
this.cars = cars;
}
}
任何幫助感激。
如果我使用帶有Jay和@ManyToMany的代碼,當嘗試插入另一輛汽車時仍然出現重複錯誤。 – JonCode