使用Liquibase处理Hibernate @ManyToOne和@OneToMany关系

4

我已经连续几个晚上在做这件事情。我想将用户中的号码(一位用户对应多个号码)与号码中的用户(多个号码对应一位用户)进行链接。但不幸的是,我一直无法成功,需要您的帮助和知识。无论我做什么,都会出现错误。请给予一个明确的解决方案。

application.properties:

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;

Liquibase:

<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>

你能分享一下你遇到的错误吗? - jazz
嵌套异常是org.hibernate.tool.schema.spi.SchemaManagementException:模式验证:表[number]中缺少列[user_id]。 - Adrian
2个回答

7
你需要解决以下两个问题:
  1. 在关系型表模型中,通常使用多对一/一对多的外键列来建模关联。因此,在你的例子中,你只需要在 number 表上添加一个外键列,而不需要在 user 表上添加。

  2. 如果你没有指定 @JoinColumn,Hibernate 会期望外键列的名称遵循这种模式:<拥有关联属性的名称>_<引用实体的主键名称>。在你的例子中,Hibernate 期望在 number 表中有一个 number_id 列。你可以在我的JPA 和 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>

2
根据我的理解,您在“number”表中将具有一个外键,该外键将代表与该号码相关联的用户。
由于您在Number实体中指定@ManyToOne关系时没有提及@JoinColumn(保存有关外键的信息的注释),因此默认情况下jpa会尝试查找名为“user_id”的列(但该列不存在)。
只需添加@JoinColumn注释并给予适当的属性即可解决问题。
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="<<name of foreign key in number table>>", refrencedColumnName = "id")

refrencedColumnName指定了在父实体中要引用的列。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接