Quarkus Hibernate中复合主键的ManyToMany关系

bhmjp9jg  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(146)

我目前正在构建一个Quarkus后端,不知道如何Map具有附加属性的ManyToMany关系。假设我有一个CorporationEntity和一个AddressEntity,我想用ManyToMany关系和一个附加属性AddressTypeMap这两个实体。我真的不知道该怎么做。
这是我目前拥有的,但由于Map错误,构建崩溃:
GenericEntity.java

@MappedSuperclass
public class GenericEntity extends PanacheEntity {
  public LocalDate createdDate;
  public LocalDate lastRevision;
}

CorporationEntity.java

@Entity
public class CorporationEntity extends GenericEntity {
  @ManyToOne public BuildingEntity airport;
  @ManyToOne public CustomerEntity customer;
  // other attributes...

CorporationHasAddressEntity.java

@Entity
public class CorporationHasAddressEntity extends PanacheEntityBase {
  @EmbeddedId
  CorporationHasAddressKey id;

  @ManyToOne
  @JoinColumn(name = "addressType_id")
  public AddressTypeEntity addressType;
}

CorporationHasAddressKey.java

@Embeddable
public class CorporationHasAddressKey implements Serializable {
  @ManyToOne
  @JoinColumn(name = "corporation_id")
  protected CorporationEntity corporation;

  @ManyToOne
  @JoinColumn(name = "address_id")
  protected AddressEntity address;
}

这是尝试构建时的例外:

java.lang.NullPointerException: Cannot invoke "org.hibernate.mapping.PersistentClass.getTable()" because "classMapping" is null

编辑:如果我调整CorporationHasAddressEntity来扩展GenericEntity,那么构建成功,但是CorporationHasAddressEntity采用PanacheEntity的ID,这只是一个整数。

imzjd6km

imzjd6km1#

事实上,我发现我犯的错误是通过阅读一篇由@ hartley链接的文章。链接到文章:https://www.baeldung.com/jpa-many-to-many
在key类中,我现在只为id声明Long变量:

@Embeddable
public class CorporationHasAddressKey implements Serializable {

  @Column(name = "corporation_id")
  protected Long corporationId;

  @Column(name = "address_id")
  protected Long addressId;
}

然后在实际的实体中,我嵌入了ID,但我也定义了ManyToOne:

@Entity
public class CorporationHasAddressEntity {
  @EmbeddedId CorporationHasAddressKey id;

  @ManyToOne
  @MapsId("corporationId")
  @JoinColumn(name = "corporation_id")
  CorporationEntity corporation;

  @ManyToOne
  @MapsId("addressId")
  @JoinColumn(name = "address_id")
  AddressEntity address;

  @ManyToOne
  @JoinColumn(name = "addressType_id")
  public AddressTypeEntity addressType;
}

这对我来说似乎很完美。再次感谢@ hartley的提示。

相关问题