我有一对一的关系,但 hibernatetool 在生成模式时会抱怨.这是显示问题的示例:
I have a one-to-one relationship but hibernatetool complains when generating the schema. Here's an example that shows the problem:
@Entity public class Person { @Id public int id; @OneToOne public OtherInfo otherInfo; rest of attributes ... }Person 与 OtherInfo 是一对一的关系:
Person has a one-to-one relationship with OtherInfo:
@Entity public class OtherInfo { @Id @OneToOne(mappedBy="otherInfo") public Person person; rest of attributes ... }Person 拥有 OtherInfo 的一方.OtherInfo 是拥有方,因此person 使用mappedBy 来指定Person 中的属性名称otherInfo".
Person is owning side of OtherInfo. OtherInfo is the owned side so person uses mappedBy to specify the attribute name "otherInfo" in Person.
在使用 hibernatetool 生成数据库架构时出现以下错误:
I get the following error when using hibernatetool to generate the database schema:
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 错误?
Any idea why? Am I a doing something wrong or is this a Hibernate bug?
推荐答案JPA 不允许在 OneToOne 或 ManyToOne 上使用 @Id 注释em> 映射.您正在尝试做的是一对一的实体关联与共享主键.最简单的情况是使用共享密钥的单向一对一:
JPA doesn't allow the @Id annotation on a OneToOne or ManyToOne mapping. What you are trying to do is one-to-one entity association with shared primary key. The simplest case is unidirectional one-to-one with shared key:
@Entity public class Person { @Id private int id; @OneToOne @PrimaryKeyJoinColumn private OtherInfo otherInfo; rest of attributes ... }这样做的主要问题是 JPA 不支持在 OtherInfo 实体中生成共享主键.经典书籍 Bauer 和 King 的 Java Persistence with Hibernate使用 Hibernate 扩展给出了以下问题的解决方案:
The main problem with this is that JPA provides no support for shared primary key generation in OtherInfo entity. The classic book Java Persistence with Hibernate by Bauer and King gives the following solution to the problem using Hibernate extension:
@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 ... }另请参阅此处.
更多推荐
JPA Hibernate 一对一关系
发布评论