JPA,复合键由外键和 table 列成员组成

JPA, Composite Key consisted of foreign key and table column members

向社区问好,

我整天都在努力寻找解决以下问题的方法。

场景如下,我有一个table

---TABLE_ONE--- INT ID VARCHAR NAME PRIMARY_KEY (ID)

和我的另一个 table 由三列组成,它们一起构成一个复合键

---TABLE_TWO--- INT TABLE_ONE_ID (FK -> TABLE_ONE.ID) VARCHAR NAME VARCHAR EMAIL PRIMARY_KEY(TABLE_ONE_ID, NAME, EMAIL)

我要实现的关系是TABLE_ONE实体会 有来自 TABLE_TWO(一对多关系)的对象列表。

我试着用如下所示的方法来做到这一点。

@Entity
@Table(name = "TABLE_ONE")
public class TableOne {

  @Column(name="id")
  private int id;
  @Column(name="name")
  private String name
  @OneToMany(fetch = FetchType.EAGER, mappedBy = "tableOne")
  private List<TableTwo> tableTwoList;
  //getters, setters, constructors        
}

@Entity
@Table(name = "TABLE_TWO")
public class TableTwo {

  @EmbeddedId
  private TableTwoCompositeId tableTwoCompositeId;
  @ManyToOne
  @JoinColumn(name = "TABLE_ONE_ID", referencedColumnName = "ID", insertable = false, updatable = false)
  private TableOne tableOne;
  //getters, setters, constructors        
}


@Embeddable
public class TableTwoCompositeId {
    @Column(name = "TABLE_ONE_ID")
    public Integer provider;
    @Column(name = "NAME")
    public String name;
    @Column(name = "EMAIL")
    public String email;
    //getters, setters, constructors
}

但是,当从数据库中检索 TableOne 对象时,我得到 javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSetCaused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist

在此先感谢您的帮助!

我认为您需要做一些小改动:

  • TableOne.id 需要一个 @Id 注释
  • TableTwoCompositeId.provider 的类型应与 TableOne.id
  • 的类型匹配
  • TableTwo.tableOne 需要一个 @MapsId 注释来表明它映射 TableTwoCompositeId.provider

代码应如下所示:

@Entity
@Table(name = "TABLE_ONE")
public class TableOne {

  @Id
  @Column(name="id")
  private int id;
  @Column(name="name")
  private String name
  @OneToMany(fetch = FetchType.EAGER, mappedBy = "tableOne")
  private List<TableTwo> tableTwoList;
  //getters, setters, constructors        
}

@Entity
@Table(name = "TABLE_TWO")
public class TableTwo {

  @EmbeddedId
  private TableTwoCompositeId tableTwoCompositeId;
  @MapsId("provider") // maps provider attribute of embedded id
  @ManyToOne
  @JoinColumn(name = "TABLE_ONE_ID", referencedColumnName = "ID", insertable = false, updatable = false)
  private TableOne tableOne;
  //getters, setters, constructors        
}


@Embeddable
public class TableTwoCompositeId {
    @Column(name = "TABLE_ONE_ID")
    public int provider;
    @Column(name = "NAME")
    public String name;
    @Column(name = "EMAIL")
    public String email;
    //getters, setters, constructors
}