java – JPA 2.1 Hibernate中的NamedSubgraph忽略了子类
作者:互联网
我正在使用Hibernate 4.3.8.FINAL并且具有以下模型,其中Department有许多Employees,Employee可以是Manager.
员工实体:
@Entity
@Table(name = "employee", schema = "payroll")
@Inheritance(strategy = InheritanceType.JOINED)
public class Employee
{
@Id
private Long id;
@Basic(optional = false)
@Column(name = "name")
private String name;
@JoinColumn(name = "department_id", referencedColumnName = "id")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Department department;
}
经理实体:
@Entity
@Table(name = "manager", schema = "payroll")
@Inheritance(strategy = InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name = "employee_id", referencedColumnName = "id")
public class Manager extends Employee
{
@Basic(optional = false)
@Column(name = "car_allowance")
private boolean carAllowance;
}
部门实体:
@NamedEntityGraph(
name = "Graph.Department.FetchManagers",
includeAllAttributes = false,
attributeNodes = {
@NamedAttributeNode(value = "name"),
@NamedAttributeNode(value = "employees", subgraph = "FetchManagers.Subgraph.Managers")
},
subgraphs = {
@NamedSubgraph(
name = "FetchManagers.Subgraph.Managers",
type = Employee.class,
attributeNodes = {
@NamedAttributeNode(value = "name")
}
),
@NamedSubgraph(
name = "FetchManagers.Subgraph.Managers",
type = Manager.class,
attributeNodes = {
@NamedAttributeNode(value = "carAllowance"),
}
)
}
)
@Entity
@Table(name = "department", schema = "payroll")
public class Department
{
@Id
private Long id;
@Basic(optional = false)
@Column(name = "name")
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "department", fetch = FetchType.LAZY)
private Set<Employee> employees;
}
如部门实体所示,我正在尝试创建一个加载所有员工的@NamedSubgraph,并且还要获取Manager.carAllowance.但是我收到以下错误:
Unable to locate Attribute with the the given name [carAllowance] on this ManagedType [com.nemea.hydra.model.test.Employee]
根据我的理解,@ NamedSubgraph.type应该用于指定要获取的实体子类属性.是否有可能Hibernate忽略了@NamedSubgraph注释的type = Manager.class属性,或者我错过了什么?
解决方法:
这可能是Hibernate 4.3.8.FINAL的缺陷,例如,当使用subgraphs属性时,EclipseLink 2.5.1不会抛出异常.
无论如何,当你在Manager类型的情况下指定subclassSubgraphs而不是子类时它应该工作,即:
@NamedEntityGraph(
name = "Graph.Department.FetchManagers",
includeAllAttributes = false,
attributeNodes = {
@NamedAttributeNode(value = "name"),
@NamedAttributeNode(value = "employees", subgraph = "FetchManagers.Subgraph.Managers")
},
subgraphs = {
@NamedSubgraph(
name = "FetchManagers.Subgraph.Managers",
type = Employee.class,
attributeNodes = {
@NamedAttributeNode(value = "name")
}
)
},
subclassSubgraphs = {
@NamedSubgraph(
name = "FetchManagers.Subgraph.Managers",
type = Manager.class,
attributeNodes = {
@NamedAttributeNode(value = "carAllowance"),
}
)
}
)
标签:java,spring,jpa,hibernate,jpa-2-1 来源: https://codeday.me/bug/20190609/1205274.html