没有ID的JPA实体 [英] JPA entity without id

查看:2237
本文介绍了没有ID的JPA实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下结构的数据库:

  CREATE TABLE实体(
id序列,
name VARCHAR(255),
PRIMARY KEY(id)
);

CREATE TABLE entity_property(
entity_id SERIAL,
name VARCHAR(255),
值TEXT
);

当我尝试创建一个EntityProperty类时



< pre $ @Entity
@Table(name =entity_property)
public class EntityProperty {

private String name;
私有字符串值;

@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:没有为实体指定标识符:package.EntityProperty 

我知道JPA实体必须有主键,但由于我无法控制的原因,我无法更改数据库模式。是否有可能创建这样的数据库模式的JPA(Hibernate)实体?

解决方案

我想你的 entity_property 有一个组合键(entity_id,name)其中 entity_id entity 的外键。如果是这样,你可以如下映射:

  @Embeddable 
public class EntityPropertyPK {
@Column (name =name)
私人字符串名称;

@ManyToOne
@JoinColumn(name =entity_id)
私人实体实体;


}

@Entity
@Table(name =entity_property)
public class EntityProperty {
@EmbeddedId
私人EntityPropertyPK ID;

@Column(name =value)
private String value;

...
}


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?

解决方案

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; 

    ...
}

这篇关于没有ID的JPA实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆