使用Criteria

时间:2017-10-28 15:37:24

标签: hibernate left-join one-to-many hibernate-criteria

我有一个Request对象,其中OneToMany映射到KPI(Request有一个KPI列表)...现在我需要使用一些参数设置的条件得到某个Request,根据数据(不是DB约束)参数传递应该只返回一个Request对象,问题是创建的hibernate查询已经将外连接留给了KPI,所以如果Request里面有5个KPI,则返回5个重复的行......我只需要一个......我怎么能实现这个

阅读代码:

        Criteria criteria = session.createCriteria(GroupKpiRequest.class);
    criteria.add(Restrictions.eq("levelCategory",LevelCategory.COMPANY));
        if(cycleNumber == 0){
            cycleNumber = getActiveCycleNo();
        }
        criteria.add(Restrictions.eq("cycleNumber",cycleNumber));

        List<GroupKpiRequest> matchingRequests = (List<GroupKpiRequest>) 
criteria.list();
        if(matchingRequests != null && matchingRequests.size() == 1 ){
            GroupKpiRequest companyRequestToDelete  = 
 matchingRequests.get(0);

请求类:

public class GroupKpiRequest {
 .
 .
 .
    @OneToMany(mappedBy="groupKpiRequest", cascade={CascadeType.ALL}, fetch=FetchType.LAZY)
    @Cascade({
    org.hibernate.annotations.CascadeType.SAVE_UPDATE,
    org.hibernate.annotations.CascadeType.DELETE,
    org.hibernate.annotations.CascadeType.MERGE,
    org.hibernate.annotations.CascadeType.PERSIST,
    org.hibernate.annotations.CascadeType.DELETE_ORPHAN//,
    org.hibernate.annotations.CascadeType.EVICT
    })
@OrderBy("groupKpiId")
@Fetch(FetchMode.SUBSELECT)
private List<GroupKPI> kpiSet;

KPI课程:

public class GroupKPI implements Serializable{
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name="CALCULATION_METHOD",referencedColumnName="METHOD_NAME")
private CalculationMethod calculationMethod;

@ManyToOne
@JoinColumns({
    @JoinColumn(name="GRP_KPI_REQ_ID",referencedColumnName="GRP_KPI_REQ_ID" , nullable=false)

    }
 )
 @Fetch(FetchMode.JOIN)
 private GroupKpiRequest groupKpiRequest;

查询:

select ..... 
from
    REQUEST this_ 
left outer join
    GROUP_KPI kpiset2_ 
        on this_.GRP_KPI_REQ_ID=kpiset2_.GRP_KPI_REQ_ID 
left outer join
    CALC_METHOD calculatio3_ 
        on kpiset2_.CALCULATION_METHOD=calculatio3_.METHOD_NAME 
left outer join
    ORGANIZATION organizati4_ 
        on this_.CYCLE_NO=organizati4_.CYCLE_NO 
        and this_.ORG_ID=organizati4_.ORG_ID 
where
    this_.deleted = 0 
    and this_.GRP_KPI_REQ_ID=? 
order by
    kpiset2_.GRP_KPI_ID asc

1 个答案:

答案 0 :(得分:0)

显然,你有left outer join原因

order by
    kpiset2_.GRP_KPI_ID asc

@OrderBy("groupKpiId")字段上有kpiSet注释的顺序的原因。

要删除重复的行,您可以尝试使用DISTINCT_ROOT_ENTITY转换器

Criteria.DISTINCT_ROOT_ENTITY vs Projections.distinct

在我看来,最好不要使用@OrderBy因为它不是一种非常灵活的方法。