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

时间:2018-08-08 13:47:31

标签: java hibernate jpa one-to-many hibernate-onetomany

对社区的问候

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

情况如下,我有一张桌子

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

我的另一个表由三列组成,这三列组成一个组合键

---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

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为您需要进行一些小的更改:

  • 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
}