我是Java新手,對Spring更新(引導和JPA)更新,但我很好奇,我試圖調試一個問題:「沒有爲實體指定標識符」。Spring JPA - 數據完整性關係
對於illustartion目的,我創建從該圖中,下表中:
最初,有一個M:N用戶和車輛臺之間的關係,所以我創建一個關聯實體(UserVehicleAsso)將它們分開。我正在關注Java中M:N映射的指南,http://viralpatel.net/blogs/hibernate-many-to-many-annotation-mapping-tutorial/
大多數情況下,它非常簡單,但我的問題是,在關聯實體(UserVehicleAsso)中,是否必須使用@Id註釋對於每個外鍵?我假設我不需要,因爲那些是從每個相應的表中自動生成的。
讓我知道你的想法或意見,謝謝。
另外,下面是我用來生成這些模型的代碼:
對於用戶表/類:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
private String fName;
private String lName;
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name="userVehicleAsso",
joinColumns={@JoinColumn(name="userID")},
inverseJoinColumns={@JoinColumn(name="vehicleID")})
private Set<Vehicle> vehicles = new HashSet<Vehicle>();
//constructor
protected User() {}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getFName() {
return fName;
}
public void setFName(String fName) {
this.fName = fName;
}
public String getLName() {
return lName;
}
public void setLName(String lName) {
this.lName = lName;
}
public Set<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(Set<Vehicle> vehicles) {
this.vehicles = vehicles;
}
@Override
public String toString() {
return getFName() + "," + getLName();
}}
用於車輛表/類:
@Entity
public class Vehicle {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int vehicleId;
private String brand;
private String model;
//foreign key mappings
//mapping with associative
@ManyToMany(mappedBy="vehicles")
private Set<User> users = new HashSet<User>();
//constructors
protected Vehicle() {}
public Vehicle(int id) {
this.vehicleId = id;
}
public Vehicle (String brand, String model) {
this.brand = brand;
this.model = model;
}
/* public Vehicle() {
}*/
public int getVehicleId() {
return vehicleId;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
@Override
public String toString() {
// + setBodyType() + "," +
return getBrand() + "," + getModel();
}
}
最後,我的關聯表/類:
@Entity
public class UserVehicleAsso{
private int userID;
private int vehicleID;
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public int getVehicleID() {
return vehicleID;
}
public void setVehicleID(int vehicleID) {
this.vehicleID = vehicleID;
}
}
你不應該有這種UserVehicleAsso實體。 – Snickers3192
你們是對的,非常感謝你! – rj2700