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

问题描述 投票:3回答:1

我需要创建一个复合键。密钥的一个属性是在MappedSuperClass中,我无法修改。密钥的另一个属性是派生类,它是一个实体类。但是,在执行下面的操作时出现运行时错误,该错误表示基类的属性(也存在于@IdClass中)不是Entity类(Derived类)的属性。请指导我如何处理这种情况。

@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。

hibernate inheritance spring-data-jpa composite-key mappedsuperclass
1个回答
1
投票

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

不要忘记使用逻辑名称(baseProp,childProp)而不是物理(base_prop,child_prop)一次。

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

}
© www.soinside.com 2019 - 2024. All rights reserved.