有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate@manytone和@OneToMany与Liquibase

我已经用了好几个晚上了。我想链接用户中的数字(一个用户到多个数字)和用户中的数字(多个数字到一个用户)。我没有运气,需要你的知识。无论我做什么,我总是在这个或那个方面出错。直截了当地回答该做什么就行了

应用程序。属性:

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) 个答案

  1. # 1 楼答案

    据我所知,您将在数字表中拥有一个外键,该外键将表示与数字关联的用户

    由于在数字实体中指定@ManyToOne关系时没有提到@JoinColumn(保存外键信息的注释),因此,默认情况下,jpa尝试在数字表中查找名为user\u id的列(该列不可用)

    只需添加注释@JoinColumn并提供适当的属性,就可以了

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="<<name of foreign key in number table>>", refrencedColumnName = "id")
    

    refrencedColumnName告诉父实体中必须引用哪个列

  2. # 2 楼答案

    有两个问题需要解决:

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

    2. 如果不指定@JoinColumn,Hibernate希望外键列的名称遵循此模式<name of the attribute that owns association>_<name of the primary key of referenced entity>。在您的示例中,Hibernate希望在number表中有一个number_id列。您可以在myUltimate 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>