小编典典

JPA hibernate一对一关系

hibernate

我有一对一的关系,但是hibernatetool在生成模式时抱怨。这是显示问题的示例:

@Entity
public class Person {
    @Id
    public int id;

    @OneToOne
    public OtherInfo otherInfo;

    rest of attributes ...
}

人与OtherInfo具有一对一关系:

@Entity
public class OtherInfo {
    @Id
    @OneToOne(mappedBy="otherInfo")
    public Person person;

    rest of attributes ...
}

人是OtherInfo的拥有方。OtherInfo是拥有方,因此person用于mappedBy在Person中指定属性名称“ otherInfo”。

使用hibernatetool生成数据库架构时出现以下错误:

org.hibernate.MappingException: Could not determine type for: Person, at table: OtherInfo, for columns: [org.hibernate.mapping.Column(person)]
        at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:292)
        at org.hibernate.mapping.SimpleValue.createIdentifierGenerator(SimpleValue.java:175)
        at org.hibernate.cfg.Configuration.iterateGenerators(Configuration.java:743)
        at org.hibernate.cfg.Configuration.generateDropSchemaScript(Configuration.java:854)
        at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:128)
        ...

知道为什么吗?我是在做错什么还是这是Hibernate错误?


阅读 245

收藏
2020-06-20

共1个答案

小编典典

JPA不允许在 OneToOneManyToOne 映射上使用 @Id 批注。您想要做的是 与共享主键*
进行一对一的实体关联。最简单的情况是使用共享密钥的单向一对一:
*

@Entity
public class Person {
    @Id
    private int id;

    @OneToOne
    @PrimaryKeyJoinColumn
    private OtherInfo otherInfo;

    rest of attributes ...
}

这样做的主要问题是JPA不支持 OtherInfo
实体中共享主键的生成。鲍尔和金所著的经典书籍《Java
Persistence with
Hibernate》
使用Hibernate扩展为问题提供了以下解决方案:

@Entity
public class OtherInfo {
    @Id @GeneratedValue(generator = "customForeignGenerator")
    @org.hibernate.annotations.GenericGenerator(
        name = "customForeignGenerator",
        strategy = "foreign",
        parameters = @Parameter(name = "property", value = "person")
    )
    private Long id;

    @OneToOne(mappedBy="otherInfo")
    @PrimaryKeyJoinColumn
    public Person person;

    rest of attributes ...
}

另外,请参阅此处

2020-06-20