问题描述
假设每个子类的继承关系表可以描述如下(来自wikibooks.org - 参见)
注意父级不是抽象的
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Project {
@ Id
私人长ID;
//其他属性
}
@Entity
@Table(name =LARGEPROJECT)
public class LargeProject扩展了Project {
私有BigDecimal预算;
$ b @Entity
@Table(name =SMALLPROJECT)
public class SmallProject extends Project {
}
我有一个场景,其中我只需要检索父级。由于性能问题,我应该做什么运行HQL查询以检索父类和只是父类而不加载任何子类?
解决方法如下所述:
定义您的父
类为 MappedSuperClass 。假设父类映射为 PARENT_TABLE
@MappedSuperClass
public abstract class AbstractParent implements Serializable {
@Id
@GeneratedValue
private long id;
@Column(table =PARENT_TABLE)
private String someProperty;
// getter's and setter's
}
对于每个子类,扩展 AbstractParent
类并定义它的 SecondaryTable 。在父类中定义的任何持久字段将被映射到由 SecondaryTable 定义的表。最后,如果需要的话使用AttributeOverrides
@Entity
@SecondaryTable(PARENT_TABLE)
public class Child扩展AbstractParent {
private String childField;
public String getChildProperty(){
return childField;
}
}
定义另一个实体检索父类
@Entity
@Table(name =PARENT_TABLE)
@ AttributeOverrides({
@AttributeOverride(name =someProperty,column = @ Column(name =someProperty))
})
public class Parent extends AbstractParent {}
没有别的。看到如上所示,我只使用JPA特定的注释
Suppose a Table per subclass inheritance relationship which can be described bellow (From wikibooks.org - see here)
Notice Parent class is not abstract
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Project {
@Id
private long id;
// Other properties
}
@Entity
@Table(name="LARGEPROJECT")
public class LargeProject extends Project {
private BigDecimal budget;
}
@Entity
@Table(name="SMALLPROJECT")
public class SmallProject extends Project {
}
I have a scenario where i just need to retrieve the Parent class. Because of performance issues, What should i do to run a HQL query in order to retrieve the Parent class and just the Parent class without loading any subclass ???
A workaround is described below:
Define your Parent
class as MappedSuperClass. Let's suppose the parent class is mapped To PARENT_TABLE
@MappedSuperClass
public abstract class AbstractParent implements Serializable {
@Id
@GeneratedValue
private long id;
@Column(table="PARENT_TABLE")
private String someProperty;
// getter's and setter's
}
For each subclass, extend the AbstractParent
class and define its SecondaryTable. Any persistent field defined in the parent class will be mapped to the table defined by SecondaryTable. And finally, use AttributeOverrides if needed
@Entity
@SecondaryTable("PARENT_TABLE")
public class Child extends AbstractParent {
private String childField;
public String getChildProperty() {
return childField;
}
}
And define another Entity with the purpose of retrieving just the parent class
@Entity
@Table(name="PARENT_TABLE")
@AttributeOverrides({
@AttributeOverride(name="someProperty", column=@Column(name="someProperty"))
})
public class Parent extends AbstractParent {}
Nothing else. See as shown above i have used just JPA specific annotations
这篇关于每个子类继承关系表:如何在不加载任何子类的情况下针对父类进行查询? (休眠)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!