我有一个具有以下结构的数据库:
CREATE TABLE entity ( id SERIAL, name VARCHAR(255), PRIMARY KEY (id) ); CREATE TABLE entity_property ( entity_id SERIAL, name VARCHAR(255), value TEXT );
当我尝试创建EntityProperty类时
@Entity @Table(name="entity_property") public class EntityProperty { private String name; private String value; @Column(name="name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="value", nullable=true, length=255) public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
我得到以下异常:
org.hibernate.AnnotationException: No identifier specified for entity: package.EntityProperty
我知道JPA实体必须具有主键,但是由于无法控制的原因,我无法更改数据库架构。是否可以创建将与这样的数据库模式一起工作的JPA(hibernate)实体?
我猜您entity_property有一个组合键(entity_id, name),其中entity_id的外键是entity。如果是这样,则可以按如下所示进行映射:
entity_property
(entity_id, name)
entity_id
entity
@Embeddable public class EntityPropertyPK { @Column(name = "name") private String name; @ManyToOne @JoinColumn(name = "entity_id") private Entity entity; ... } @Entity @Table(name="entity_property") public class EntityProperty { @EmbeddedId private EntityPropertyPK id; @Column(name = "value") private String value; ... }