java Hibernate继承:如何知道查询返回的子类?
我使用Hibernate和3.6以及Spring数据JPA1.5。我有一个上层阶级:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Mother{
private long id;
// constructor, others attributes and accessors
}
@Entity
public class FirstSubClass extends Mother{
private String specificFirstSubClassNotNull;
// constructor, others attributes and accessors
}
@Entity
public class SecondSubClass extends Mother{
private String specificSecondSubClassNotNull;
// constructor, others attributes and accessors
}
我使用spring data jpa从数据库中获取数据,我想获取所有的母对象。我能从数据中提取数据。Spring data jpa返回给我一个母亲列表(列出母亲)。所以我想知道哪一个是知道哪个子类是母亲的最佳解决方案? 这是第一个解决方案吗:
for(Mother mother : mothers){
if(mother instanceof FirstSubClass){
System.out.println("This is a FirstSubClass instance");
}else if(mother instanceof SecondSubClass){
System.out.println("This is a SecondSubClassinstance");
}
}
或者第二种解决方案:
for(Mother mother : mothers){
if(mother.getSpecificFirstSubClassNotNull!=null){
System.out.println("This is a FirstSubClass instance");
}else if(getSpecificSecondSubClassNotNull!=null){
System.out.println("This is a SecondSubClassinstance");
}
}
我认为以上这些都不好。你会怎么做?欢迎任何提议。 谢谢
# 1 楼答案
为了应用某个特定的行为,需要向下投射,这是一种代码气味。毕竟,使用继承有很好的理由,因此应该利用OOP提供的功能:多态性
您的域模型不必是其关联数据库表的一对一镜像。您可以向实体添加域逻辑,这就是应用特定类型行为的方式
假设您有以下层次结构:
获取母实体列表时,只需调用基类方法,并依赖多态性来实现特定的类型行为: