代码之家  ›  专栏  ›  技术社区  ›  tenticon

使用JPA和Hibernate时如何避免超类查询中的多态性

  •  3
  • tenticon  · 技术社区  · 7 年前

    Customers LegacyCustomers .

    客户 延伸 法律客户 加入一些 额外的 柱。

    @Entity
    @Table(name="Customers")
    public class Customers extends LegacyCustomers {
        @Column(name="NewId") private String newId;
        @Column(name="PhoneNumber") private String phoneNumber;
    }
    
    @Entity
    @Table(name="LegacyCustomers")
    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    public class LegacyCustomers {
        @Column(name="OldId") private String oldId;
        @Column(name="Name") private String name;
        @Column(name="Address") private String address;
    } 
    

    然而,它们是完全不同的表。我正在寻找一种用java表达关系的方法,但要避免hibernate在查询超类表时创建的多态性( 法律客户 ). 当我查询时,如何告诉hibernate只使用超类中的列 ?

    不幸的是 @Polymorphism 建议的注释 here 没用。

    谢谢你的帮助

    1 回复  |  直到 7 年前
        1
  •  3
  •   Vlad Mihalcea    7 年前

    要实现您的目标,您需要使用 @MappedSuperclass 注释,而不是新的 BaseCustomers 类,该类封装公共属性:

    @MappedSuperclass
    public class BaseCustomers {
        @Column(name="OldId") private String oldId;
        @Column(name="Name") private String name;
        @Column(name="Address") private String address;
    }
    

    之后, LegacyCustomers 只需延长时间 并且只添加了 @Entity 基本客户 未被视为实体:

    @Entity
    @Table(name="LegacyCustomers")
    public class LegacyCustomers extends BaseCustomers {
    
    }
    

    Customers

    @Entity
    @Table(name="Customers")
    public class Customers extends BaseCustomers {
        @Column(name="NewId") private String newId;
        @Column(name="PhoneNumber") private String phoneNumber;
    }
    

    就这样。