java - 具有 @EmbeddedId 、 @GeneratedValue 和 @ManyToOne 的实体

标签 java hibernate jpa jpa-2.0 composite-key

我使用 postgres 数据库,我有一个 Conventionnement 实体,它与约定和组织有 ManyToOne 关系,我想创建 3 个主键 convention_idorganization_idGeneratedValue id,我像下面的示例一样使用了 @Embeddable,但出现了以下错误

Caused by: org.hibernate.annotations.common.AssertionFailure: Declaring class is not found in the inheritance state hierarchy: ConventionnementIdentity

当我在 Conventionnement 类中移动 id 时出现此错误

ConventionnementIdentity must not have @Id properties when used as an @EmbeddedId

@Entity
@Table(name = "conventionnement")
public class Conventionnement implements Serializable {

    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private ConventionnementIdentity conventionnementIdentity;

    @MapsId("convention_id")
    @ManyToOne
    private Convention convention;

    @MapsId("organization_id")
    @ManyToOne
    private Organization organization;

    //getter and setter
}

@Embeddable
public class ConventionnementIdentity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "convention_id", insertable = false, updatable = false)
    private Long conventionId;

    @Column(name = "organization_id", insertable = false, updatable = false)
    private Long organizationId;

    //getter and setter
}

最佳答案

您已经定义了一个 @EmbeddedId,但在其中声明了另一个 @Id,因此出现错误。使生成的 id 指向表中正确的 id 列(下面我假设“id”作为列名):

@Embeddable
public class ConventionnementIdentity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator", sequenceName="YOUR_DB_SEQ", allocationSize=1)
    private Long id;

    @Column(name = "convention_id", insertable = false, updatable = false)
    private Long conventionId;

    @Column(name = "organization_id", insertable = false, updatable = false)
    private Long organizationId;

    //getter and setter
}

关于java - 具有 @EmbeddedId 、 @GeneratedValue 和 @ManyToOne 的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49465335/

相关文章:

java - 监控 BufferedInputStream 下载进度

java.sql.SQLException : "Driver does not support this function" 异常

java - 单向关系 : Remove cascade

java - 如果违反约束,CrudRepository saveAll 方法将引发异常

java - 什么时候使用 EntityManager 的 createQuery() 和 find() 方法?

java - JPA ORM - 与 OneToOne 映射的混淆

java - toplink 未创建一张表

java - 需要帮助分析 Java 线程转储

java - 如何从列表中取出列表?

java - 为什么 Maven 不打包我的 hibernate 映射文件?