edm*_*lia 4 java spring hibernate jpa jpa-2.1
我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
经理实体:
@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;
}
Run Code Online (Sandbox Code Playgroud)
部门实体:
@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;
}
Run Code Online (Sandbox Code Playgroud)
如部门实体所示,我正在尝试创建一个加载所有员工的@NamedSubgraph,并且还要获取Manager.carAllowance.但是我收到以下错误:
Unable to locate Attribute with the the given name [carAllowance] on this ManagedType [com.nemea.hydra.model.test.Employee]
Run Code Online (Sandbox Code Playgroud)
根据我的理解,@ NamedSubgraph.type应该用于指定要获取的实体子类属性.是否有可能Hibernate忽略了@NamedSubgraph注释的type = Manager.class属性,或者我错过了什么?
这可能是Hibernate 4.3.8.FINAL的缺陷,例如EclipseLink 2.5.1在使用subgraphs属性时不抛出异常.
无论如何,它应该在您指定subclassSubgraphs而不是subclass在Manager类型的情况下工作,即:
@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"),
}
)
}
)
Run Code Online (Sandbox Code Playgroud)