我在后端应用程序中定义了一些实体,它们具有一对@ManytoOne和@OneToMany关系,但是每个以psequel执行的操作,每个外键和主键关系都创建了其他结构。而且我在执行时看到此异常,我不确定如何还原
休眠:创建表user_locations(user_id int4不为null, location_id int4不为null)休眠:更改表(如果存在) location_user_id添加约束FKfsq9me9k3dj93oujbfgplkfrx外部 键(user_id_id)引用用户2019-04-08 15:18:29.001 WARN 2023 --- [main] o.h.t.s.i.ExceptionHandlerLoggedImpl:GenerationTarget遇到异常接受命令:错误 如果存在location_user_id,则执行“ DDL”更改表 FKfsq9me9k3dj93oujbfgplkfrx外键(user_id_id)引用用户” 通过JDBC语句
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table if exists location_user_id add constraint
FKfsq9me9k3dj93oujbfgplkfrx外键(user_id_id)引用用户” 通过JDBC语句
这是我的User表的样子:
@Entity
public class User {
private String gmailToken;
private String emailAddress;
@Id
private int Id;
@ManyToMany
private List<Location> locations;
}
位置实体看起来像这样:
@Entity
public class Location {
private String name;
private String country;
private String countryCode;
private Point geoCordinates;
private double googleRating;
private String phoneNumber;
private ArrayList workingHours = new ArrayList<WorkingHours>();
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int Id;
@ManyToMany
private List<User> userId;
}
这里缺少什么吗?
编辑后添加:
我将用户实体更改为如下形式:
public class User {
private String gmailToken;
private String emailAddress;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int Id;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="USER_ID")
private List<Location> locations;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="USER_ID")
private List<ReviewRequest> reviewRequests;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="USER_ID")
private List<Response> responseForRequests;
public User(String gmailToken){
this.gmailToken =gmailToken;
}
}
位置实体看起来像这样:
公共类位置{
private String name;
private String country;
private String countryCode;
private Point geoCordinates;
private double googleRating;
private String phoneNumber;
private ArrayList workingHours = new ArrayList<WorkingHours>();
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int Id;
@ManyToMany(mappedBy = "location")
private List<User> userId;
@OneToMany(mappedBy = "location")
private List<Customer> customerId;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="LOCATION_ID")
private List<ReviewRequest> reviewId;
}
在创建单个表和在给定的User表中创建外键列时,我仍然遇到问题。
看起来好像appedBy和@JoinColumn似乎不正确?
答案 0 :(得分:1)
1)您应该在关系的拥有方指定@JoinTable
(除非您对休眠命名默认设置没问题)
2)通过在实体之一上添加mappedBy
来指定拥有方:
@ManyToMany
private List<Location> locations;