Hibernate 注释映射与复合主键的一对一单向关联

Hibernate annotations to map one to one unidirectional association with composite primary key

我有两个 table:报告和扉页。报告由 'id' 和 'index' 标识,它们是 flyleaf table.

中的外键和主键

table 的架构是:

CREATE TABLE `report` (
   `id` int(11) NOT NULL,
   `index` varchar(5) NOT NULL,
   `nb_page` int(11) DEFAULT NULL
); 
ALTER TABLE `report` ADD PRIMARY KEY (`id`,`index`);

CREATE TABLE `flyleaf_t` (
   `id` int(11) NOT NULL,
   `index` varchar(5) NOT NULL,
   `title` varchar(30) DEFAULT NULL,
   `author` varchar(30) DEFAULT NULL,
   `checker` varchar(30) DEFAULT NULL
);
ALTER TABLE `flyleaf` ADD PRIMARY KEY (`id`,`index`);
ALTER TABLE `flyleaf` ADD CONSTRAINT `flyleaf_ibfk_1` FOREIGN KEY (`id`,`index`) REFERENCES `report` (`id`, `index`);

我使用 Hibernate 注释以单向方式映射此关联。当我使用简单键(非复合键)时,它显然运行良好,但是当我尝试使用复合键时,会抛出 "org.hibernate.TypeMismatchException" 消息:"Provided id of the wrong type for class lgmi_cr.Flyleaf. Expected: class lgmi_cr.Flyleaf, got class lgmi_cr.Report"

如果有人已经看到相同的案例或知道如何以单向一对一的方式表示这种关联,我们将不胜感激。

编辑: 这就是我做映射的方式

@Entity
@Table(name="report")
public class Report implements Serializable{

    @Id
    @Column(name = "id")
    private int id;

    @Id
    @Column(name = "index")
    private String index;

    @OneToOne 
    @JoinColumns({@JoinColumn(name="id", referencedColumnName="id"),
            @JoinColumn(name="index", referencedColumnName="index")})
    private Flyleaf flyleaf;
...

@Entity
@Table(name="flyleaf")
public class Flyleaf implements Serializable {

    @Id
    @Column(name = "id")
    private int id;

    @Id
    @Column(name = "index")
    private String index;
....

我遇到了这个异常"org.hibernate.TypeMismatchException: Provided id of the wrong type for class lgmi_cr.Flyleaf. Expected: class lgmi_cr.Flyleaf, got class lgmi_cr.Report"

我希望您能分享一下您是如何在 Hibernate 中映射这些关系的?我会这样做:

1) 使用@Embeddable 注释将每个复合 table 映射为单独的 class 对象,例如:

@Embeddable
public class ReportPK implements Serializable {

  @Basic(optional = false)
  @Column(name="id")
  private int id;
  @Basic(optional = false)
  @Column(name="index")
  private String index;
...

实体 class 看起来像:

@Table(name="report")
public class Report implements Serializable {

  @EmbeddedId
  protected ReportPK id;
...

2) 在扉页实体class中,可以添加单向映射为:

@OneToOne
  @JoinColumns({
    @JoinColumn(name="id",
      referencedColumnName="id"),
    @JoinColumn(name="index",
      referencedColumnName="index"),
  })
  private Report report;
...

如果这没有帮助,也许您可​​以更具体一些。 :-)