使用 POJO 作为休眠实体的基础

Using POJO as a base for hibernate entity

我最近才开始用Java开发,我的客户也是Java发布以来一直在开发的开发者。

所以当他说“我们有充分的理由为什么不在我们的项目中使用瞬态字段”时,我没有问这些原因是什么。但是,回到问题:

我有两个 classes:

  1. POJO,仅用于生成JSON:
public class BaseSector implements Serializable {

    private String id;

    private String name;

    private String parentId;
  1. 实体:
public class Sector {

    @Column(length = 36)
    private String id;

    @Column(length = 40)
    private String name;

    @Column(length = 36)
    private String parentId;
//  ... Bunch of other fields

实体 class 有没有办法扩展这个 POJO,并动态添加列注释?或者有 POJO 作为接口?或者在 POJO 构造函数中使用实体 class?

早些时候我们有这样的事情:

for (Sector sector : sectors) {
    BaseSector baseSector = new BaseSector();
    baseSector.setId(sector.getId());
    baseSector.setName(sector.getName());
    baseSector.setParentId(sector.getParentId());
}

但是我通过在 HQL 构造函数中使用 BaseSector 改变了它... 顺便说一句,我们还有 SectorInfo 和 SimpleSectorInfo,它们也扩展了 BaseSector,但这是一个不同的主题..

TRANSIENT 字段告诉您的 ENTITY class 该特定字段不应保留在数据库中。 @Transient 注释用于忽略一个字段以不在 JPA 中保留在数据库中,而 transient 关键字用于从序列化中忽略一个字段。用@Transient注解的字段仍然可以序列化,但是用transient关键字声明的字段不被持久化,不被序列化。

POJO 可以通过 ENTITY 和 vice-versa 进行扩展。这在 JPA specification.You 中有说明,可以在以下链接中找到更多示例:

Link:1 : JPA Non-Entity SuperClass

Link 2 : JPA Specification

您可以使用注释来实现此目的:@javax.persistence.MappedSuperclass

它声明:A superclass 被视为 non-entity class 如果没有与映射相关的注释,例如 @Entity 或 @MappedSuperclass在class级别使用。

这意味着如果您不在 superclass.[=20 中使用上述注释,您的 superclass 将被视为 non-entity class =]

如何构建 classes :

SUPERCLASS 这也是您的 JSON 对象

POJO
@MappedSuperclass
public class BaseSector implements Serializable {

    private String id;
    private String name;
    private String parentId;

}

实体 class :

@Entity
@Table(name = "sector")
public class Sector extends BaseSector {
    @Column(length = 36)
    private String id;

    @Column(length = 40)
    private String name;

    @Column(length = 36)
    private String parentId;

    //  ... Bunch of other field

}

您还可以在您的 ENTITY - Sector 中覆盖一些由 BaseSector 定义的 属性 您需要使用

 @AttributeOverride   // for single property
 @AttributeOverrides  // override more than one property