java - 使用 Liquibase 休眠 @ManyToOne 和 @OneToMany
问题描述
我已经为此工作了几个晚上。我想将用户中的号码(一个用户到多个号码)与用户中的号码(多个号码到一个用户)联系起来。我没有运气,需要你的知识。无论我做什么,我总是会遇到这个或那个错误。直接回答该做什么就可以了。
应用程序属性:
spring.jpa.hibernate.ddl-auto=validate
用户实体:
@Entity
@Table(name = "user")
public class Users implements Serializable {
private static final long serialVersionUID = 2323232323L;
@Id
@Column(nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private List<Number> number;
编号实体:
@Entity
@Table(name = "number")
public class Number implements Serializable {
private static final long serialVersionUID = 1212121212L;
@Id
@Column(nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(cascade = CascadeType.ALL)
private Users user;
液基:
<createTable tableName="user">
<column name="id" type="BIGINT(8)" autoIncrement="true">
<constraints nullable="false" primaryKey="true"/>
</column>
<column name="fk_number" type="BIGINT"/>
</createTable>
<createTable tableName="number">
<column name="id" type="BIGINT(8)" autoIncrement="true">
<constraints nullable="false" primaryKey="true"/>
</column>
<column name="user" type="BIGINT"/>
</createTable>
解决方案
您需要解决 2 个问题:
在关系表模型中,您通常为多对一/一对多关联与多端的外键列建模。因此,在您的示例中,您只需要在
number
表上而不是在user
表上的外键列。如果您不指定 a
@JoinColumn
,Hibernate 期望外键列的名称遵循此模式<name of the attribute that owns association>_<name of the primary key of referenced entity>
。在您的示例中,Hibernate 需要表number_id
中的一列number
。您可以在我的Ultimate Guide - Association Mappings with JPA and Hibernate中了解有关关联映射的更多信息。
如果您保留实体映射并使用此表定义,它应该可以工作:
<createTable tableName="user">
<column name="id" type="BIGINT(8)" autoIncrement="true">
<constraints nullable="false" primaryKey="true"/>
</column>
</createTable>
<createTable tableName="number">
<column name="id" type="BIGINT(8)" autoIncrement="true">
<constraints nullable="false" primaryKey="true"/>
</column>
<column name="user_id" type="BIGINT"/>
</createTable>
推荐阅读
- oracle - oracle 12c 使用 puppet 自动安装返回错误,但手动运行时正常
- c - 从 C 程序构建新的二进制文件
- c# - MOQ 单元测试错误。预期在模拟上调用一次,但为 0 次
- python - 字符串到 int ValueError Python
- linux - 标准输出中如何管理内存?
- java - 在 Android 中使用 Room 和 RxJava 链接多个网络调用和数据库插入
- java - 创建没有旋转元数据的旋转pdf文件
- javascript - Firebase 当前用户更新电话号码
- java - 如何将本机查询结果映射到自定义类对象?
- excel - 试图制作一个公式来识别另一个是否为空白,然后添加一个数字 [Excel]