我有一个一对多的关系实体场景就像这样 EmployeeGroupActivity 有很多 EmployeeActivity Hibernate 映射如下
@Entity
@Table(name = “employeegroupactivity”)
@DynamicUpdate
public class EmployeeGroupActivity{
/**
*
*/
private static final long serialVersionUID = -9114620718714111316L;
private Integer groupActivityId;
private Set<EmployeeActivity> employeeActivities;
public EmployeeGroupActivity(){
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "groupActivityId")
public Integer getGroupActivityId() {
return groupActivityId;
}
public void setGroupActivityId(Integer groupActivityId) {
this.groupActivityId = groupActivityId;
}
@OneToMany(targetEntity = EmployeeActivity.class,mappedBy = "groupEmployeeActivity",fetch = FetchType.LAZY)
public Set<EmployeeActivity> getEmployeeActivities() {
return employeeActivities;
}
public void setEmployeeActivities(Set<EmployeeActivity> employeeActivities) {
this.employeeActivities = employeeActivities;
}
}
// EmployeeActivity
@Entity
@Table(name = "employeeactivity")
@DynamicUpdate
public class EmployeeActivity{
private Integer empActivityId;
String activityDescription;
Date activityDate;
private Integer eventId;
private EmployeeGroupActivity groupEmployeeActivity; //This is mapped as ManyToOne
}
// Query Part
Criterion eventIdCriterion = Restrictions.eq(“EG.eventId", eventId);
Projection projection = Projections.projectionList()
.add(Projections.property(“EG.groupActivityId"),"groupActivityId")
.add(Projections.property("EMPACT.empActivityId”), "employeeActivities.empActivityId")
.add(Projections.property("EMPACT.activityDescription”), "employeeActivities.activityDescription")
.add(Projections.property("EMPACT.activityDate"), "employeeActivities.activityDate");
Criteria criteria = sessionObject.createCriteria(EmployeeGroupActivity.class,”EG")
.createAlias(“EG.employeeActivities", “EMPACT”)
.setProjection(projection)
.add(eventIdCriterion);
criteria
.setResultTransformer(new AliasToBeanNestedResultTransformer(
GroupActivityResponse.class));
当我使用 where 子句获取 EmployeeGroupActivity 时,我期望一个 EmployeeGroupActivity 用于具有许多 EmployeeActivity 对象的事件。
但是我得到的结果是许多 EmployeeGroupActivity 对象都具有相同的 groupActivityId 但每个对象在一组 EmployeeActivity 中有一个 EmployeeActivity 对象。
仅当我使用具有休眠标准的投影时才会发生这种情况,如果我不使用投影,我将获得一个具有许多 EmployeeActivity 对象的 EmployeeGroupActivity 对象。
我正在使用 setResultTransformer 作为标准和http://stackoverflow.com/questions/20331852/java-hibernate-transformer-aliastobeannestedresulttransformer
一些在 SO 中发布的库
如何通过预测获得一组员工活动?我有很多这样的要求,我必须在每个地方迭代结果并让一个根对象添加所有设置项,然后作为响应返回,这需要大量迭代。
更新:请注意 DISTINCT_ROOT_ENTITY 不起作用