使用JPA覆盖@MappedSuperclass中定义的@Id

Sus*_*ant 6 java hibernate jpa hibernate-mapping mappedsuperclass

我有一个AbstractEntity类,它由我的应用程序中的所有实体扩展,基本上充当标识符提供者.

@MappedSuperclass
public class AbstractEntity implements DomainEntity {

    private static final long serialVersionUID = 1L;

    /** This object's id */
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected long id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="creation_date", nullable = false, updatable=false)
    private Date creationDate = new Date();

    /**
     * @return the id
     */
    public long getId() {
        return this.id;
    }

    /**
     * @param id the id to set
     */
    public void setId(long id) {
        this.id = id;
    }
}
Run Code Online (Sandbox Code Playgroud)

我现在有一个案例,我需要为我的几个实体类定义一个单独的Id,因为这些需要有一个自定义的序列生成器.怎么能实现这一目标?

@Entity
@Table(name = "sample_entity")
public class ChildEntity extends AbstractChangeableEntity {

    @Column(name = "batch_priority")
    private int priority;

    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }

}
Run Code Online (Sandbox Code Playgroud)

}

Vla*_*cea 6

你不能这样做.如果需要,请检查此GitHub示例.

@Id在基类中定义后,您将无法在子类中重写它,这意味着最好将@Id责任留给每个具体的类.

有关更多详细信息,请查看此文章.


Ala*_*Hay 5

拆分您的基类。

定义除 ID 之外的所有常见字段:

@MappedSuperclass
public  abstract class AbstractEntityNoId implements DomainEntity {
 private static final long serialVersionUID = 1L;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="creation_date", nullable = false, updatable=false)
    private Date creationDate = new Date();
}
Run Code Online (Sandbox Code Playgroud)

使用默认 ID 生成器扩展上述内容:

@MappedSuperclass
public abstract class AbstractEntity extends AbstractEntityNoId {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected Long id;

    public Long getId(){
       return id;
    }
}
Run Code Online (Sandbox Code Playgroud)

需要自定义 ID 生成的类扩展了前者,其他类扩展了后者。

有了上述内容,除了需要生成自定义 ID 的实体之外,无需更改现有代码。