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

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

问题描述

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

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
);

当我尝试创建 EntityProperty 类时

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;
    }
}

我收到以下异常:

org.hibernate.AnnotationException: No identifier specified for entity: package.EntityProperty

我知道 JPA 实体必须有一个主键,但由于我无法控制的原因,我无法更改数据库架构.是否可以创建与这样的数据库模式一起使用的 JPA(休眠)实体?

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?

推荐答案

我猜你的 entity_property 有一个复合键 (entity_id, name) 其中 entity_identity 的外键.如果是这样,您可以将其映射如下:

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天全站免登陆