我使用 spring jpa+hibernate 连接到具有 2 个表的 Oracle 数据库:Customers
和 LegacyCustomers
.
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 在查询父类(super class)表 ( LegacyCustomers
) 时创建的多态性。当我查询 LegacyCustomers
时,如何告诉 Hibernate 仅使用父类(super class)中的列?
不幸的是@Polymorphism
建议注释 here没有帮助。罢工>
感谢帮助
最佳答案
为了实现您的目标,您需要使用 @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
只是扩展了 BaseCustomers
并且只添加了 @Entity
注释,因为 BaseCustomers
是不被视为一个实体:
@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;
}
就是这样。
关于java - 使用 JPA 和 Hibernate 时如何避免父类(super class)查询中的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53675530/