首页 > 解决方案 > 使用 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>

标签: javahibernatespring-bootjpaliquibase

解决方案


您需要解决 2 个问题:

  1. 在关系表模型中,您通常为多对一/一对多关联与多端的外键列建模。因此,在您的示例中,您只需要在number表上而不是在user表上的外键列。

  2. 如果您不指定 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>

推荐阅读