无法通过hibernate注释正确映射实体

时间:2017-09-07 17:16:09

标签: java hibernate

我有一个Invoice实体,它包含另一个实体 - Counterparty和另一个实体的列表 - Items。在设置项目清单和发票之间建立关系时,没有问题。但是,当我尝试在发票实体和交易对手实体之间建立类似的关系时,我收到错误:

@OneToOne or @ManyToOne on pl.coderstrust.model.Invoice.counterparty references an unknown entity: pl.coderstrust.model.counterparty.Counterparty

这是我的发票,预计只包含一个交易对手和一个项目列表。

@Entity
@Table(name = "invoices")
public class Invoice implements Comparable<Invoice>, Serializable {

      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "invoice_id")
      private int id;

      @Column(name = "date")
      private LocalDate date = LocalDate.now();

      @ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
          CascadeType.REFRESH})
      @JoinColumn(name = "nip")
      private Counterparty counterparty;

      @OneToMany(mappedBy = "invoice", cascade = {CascadeType.PERSIST, CascadeType.MERGE,
          CascadeType.DETACH, CascadeType.REFRESH})
      @JsonBackReference
      private List<InvoiceItem> invoiceItems = new ArrayList<>();

这是我的商品实体,可与一张发票相关:

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "item_id")
  private int id;
  private String description;
  private int numberOfItems;
  private BigDecimal amount;
  private BigDecimal vatAmount;

  @JoinColumn(name = "vat_code")
  @Enumerated(EnumType.ORDINAL)
  private Vat vat;

  @OneToOne(mappedBy = "invoice_id", fetch = FetchType.EAGER, cascade = {CascadeType.DETACH,
      CascadeType.MERGE, CascadeType.PERSIST,
      CascadeType.REFRESH})
  @JsonManagedReference
  private Invoice invoice;

这是我的对手方,应该与许多发票有关:

@Entity
@Table(name = "counterparties")
public class Counterparty implements Serializable {

  @Id
  @Column(name = "nip")
  private String nip;
  private String companyName;
  private String phoneNumber;
  private String bankName;
  private String bankNumber;
  @OneToOne(fetch = FetchType.LAZY, mappedBy = "counterparty", cascade = CascadeType.ALL)
  private Address address;

  @OneToMany(mappedBy = "counterparty", fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST,
      CascadeType.MERGE,
      CascadeType.DETACH, CascadeType.REFRESH})
  private List<Invoice> invoices;

发票对手关系有什么问题?

1 个答案:

答案 0 :(得分:0)

当类没有添加到hibernate配置时,通常会抛出Hibernate错误。需要先将Hibernate告知所有作为实体的类,然后才能使用它们。

如何使您的类知道Hibernate?即通过将类添加到Configuration对象:

configuration.addClass(Counterparty.class);

或者将类添加到使用Spring时扫描实体的包中?

另一方面说明:Item类似乎有些奇怪吗?它指定与Invoice的OneToOne关系;如果这不是ManyToOne(意味着单个发票可以有0个或更多项)?