java - 为什么@ManytoOne 或@OnetoMany 在 SpringBoot 中创建问题
问题描述
我在我的后端应用程序中定义了一些实体,它们有几个 @ManytoOne 和 @OneToMany 关系,但每次执行后,每个外键和主键关系都创建了额外的结构。我在执行时看到了这个异常我不知道如何恢复
Hibernate:创建表 user_locations(user_id int4 not null,locations_id int4 not null) Hibernate:如果存在则更改表 location_user_id 添加约束 FKfsq9me9k3dj93oujbfgplkfrx 外键(user_id_id)引用用户 2019-04-08 15:18:29.001 WARN 2023 --- [ main ] ohtsiExceptionHandlerLoggedImpl:GenerationTarget 遇到异常接受命令:通过 JDBC 语句执行 DDL“如果存在 location_user_id 添加约束 FKfsq9me9k3dj93oujbfgplkfrx 外键(user_id_id)引用用户时出错”
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table if exists location_user_id add constraint
FKfsq9me9k3dj93oujbfgplkfrx 外键(user_id_id)引用用户”通过 JDBC 语句
这就是我的用户表的样子:
@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;
}
我仍然面临在给定的用户表中创建单个表和创建外键列的问题。
看起来 mappedBy 和 @JoinColumn 似乎不正确?
解决方案
1)您应该指定@JoinTable
关系的拥有方(除非您可以使用休眠命名默认值)
2)mappedBy
通过添加以下实体之一来指定拥有方:
@ManyToMany
private List<Location> locations;
推荐阅读
- charts - 水平轴标签未使用 100% 宽度(谷歌图表)
- maven - Intellij 无法导入类
- microsoft-cognitive - Azure-cognitive-services 给出“404 资源未找到”
- xml - 如何通过过滤oracle中的节点来更新xml?
- dialogflow-es - 在我的 Google Action 中更新单词的发音
- java - 按住箭头键时,TableView 出现故障
- typescript - TypeScript 中泛型类类型属性的简写
- c++ - 如何在 Qt Creator 5.13 中使用 std::filesystem
- python - 如何使用字符串列表中的数据创建日期?
- python-3.x - 在数据框中具有最小和最大条件值时,我可以使用一个函数吗?