hibernate - 如何使用 spring-jpa 创建复合键,其中键的一个属性在 @MappedSuperClass 中,而其他属性在 @Entity 类中?

标签 hibernate inheritance spring-data-jpa composite-key mappedsuperclass

我需要创建一个组合键。键的一个属性在我无法修改的 MappedSuperClass 中。键的另一个属性在作为实体类的派生类中。但是,我在执行以下命令时遇到运行时错误,该错误表明基类的属性(也存在于@IdClass 中)不是实体类(派生类)的属性。请指导我如何处理这种情况。

@MappedSuperClass
public abstract class Base
{
    @Id
    protected String id;
}

@Entity
@Idclass(DerivedPK.class)
public Derived extends Base
{
    @Id
    protected float version;
}

public class DerivedPK
{
    private String id;
    private float version;
}

我收到一条错误消息,指出 DerivedPK 中存在的属性“id”在类“Derived”中找不到。使用的 Hibernate 版本是 4.1.1.Final。

最佳答案

这可以使用下面提到的示例代码来实现。

Do not forget to make use of logical names (baseProp, childProp) instead of physical (base_prop, child_prop) once.

@Data 和@EqualsAndHashCode(callSuper = true) 这些是 lombok 提供的注解,可以减少为所有实体属性编写 getter 和 setter 的开销。

示例:

@Data
@MappedSuperclass
public class BaseEntity {

  protected Long baseProp;

}

@Data
@Entity
@EqualsAndHashCode(callSuper = true)
@Table(uniqueConstraints = {
    @UniqueConstraint(columnNames = {"baseProp", "childProp"})
})
public class ChildEntity extends BaseEntity {

@Id
private Long id;

private String childProp;

}

关于hibernate - 如何使用 spring-jpa 创建复合键,其中键的一个属性在 @MappedSuperClass 中,而其他属性在 @Entity 类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20297106/

相关文章:

javascript继承——从抽象思想到实际代码

java - 使用接口(interface)的抽象类或公共(public)方法

java - 如何将 Spring Boot 应用程序正确连接到 Elasticsearch 6.1?

java - 如何获取 @ElementCollection map 的相关表

mysql - 无法连接到 MySQL 的 Spring Boot 应用程序故障排除

多重继承中的Python self和super

java - 包 org.springframework.data.repository 不存在 spring boot jpa

java - 有没有办法在使用 Spring Data JPA 的查询中使用列名作为参数?

java - JPA @ManyToOne - EntityNotFoundException 或 null 值?

java - JpaRepository 查找子级(可分页)