java—使用pojo作为hibernate实体的基础

1rhkuytd  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(284)

我最近开始用java开发,我的客户也是一个开发人员,自从java发布以来,他一直在用java开发。
所以当他说“我们有一个很好的理由为什么不在我们的项目中使用 transient 场”时,我并没有问这些理由是什么。但是,回到问题上来:
我有两个班:
pojo,仅用于生成json:

public class BaseSector implements Serializable {

    private String id;

    private String name;

    private String parentId;

实体:

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

实体类有没有办法扩展这个pojo并动态添加列注解?或者将pojo作为接口?或者在pojo构造函数中使用实体类?
早些时候我们有过这样的经历:

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,但这是另一个主题。。

2vuwiymt

2vuwiymt1#

一个临时字段告诉您的实体类,这个特定的字段不应该持久化在数据库中。 @Transient 注解用于忽略一个字段,使其不在jpa中的数据库中持久化,其中 transient 用于从序列化中忽略字段的关键字。带注解的字段 @Transient 仍然可以序列化,但用 transient 关键字不被持久化和不被序列化。
pojo可以由实体扩展,反之亦然。这在jpa规范中有说明。您可以在以下链接中找到更多示例:
link:1 :jpa非实体超类
链接2:jpa规范
您可以通过使用注解来实现这一点: @javax.persistence.MappedSuperclass 它指出:如果在类级别上没有使用诸如@entity或@mappedsuperclass之类的Map相关注解,则超类被视为非实体类。
这意味着您的超类将被视为一个非实体类在这里,如果您不使用上述注解在您的超类。
如何构造类:
超类,它也是json对象的pojo

@MappedSuperclass
public class BaseSector implements Serializable {

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

}

实体类:

@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

}

您还可以重写需要使用的实体扇区中由basesector定义的某些属性

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

相关问题