Issue
I have a database with the following structure:
CREATE TABLE entity (
id SERIAL,
name VARCHAR(255),
PRIMARY KEY (id)
);
CREATE TABLE entity_property (
entity_id SERIAL,
name VARCHAR(255),
value TEXT
);
When I try to create an EntityProperty class
@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;
}
}
I get the following exception:
org.hibernate.AnnotationException: No identifier specified for entity: package.EntityProperty
I know that JPA entities must have a primary key but I can't change the database schema due to reasons that are beyond my control. Is it possible to create JPA (Hibernate) entities that will work with database schema like this?
Solution
I guess your entity_property
has a composite key (entity_id, name)
where entity_id
is a foreign key to entity
. If so, you can map it as follows:
@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;
...
}
Answered By - axtavt
Answer Checked By - Cary Denson (JavaFixing Admin)