org.hibernate.QueryException: Criteria objects can

2019-09-14 18:45发布

问题:

I face above issue when try to sort based on an embedded field;

eg: I try to sort with the property tObservation.raw.waterLevel.metre. But getting following exception.

Caused by: org.hibernate.QueryException: Criteria objects cannot be created directly on components.  Create a criteria on owning entity and use a dotted property to access component property: tObservation.raw
    at org.hibernate.loader.criteria.CriteriaQueryTranslator.getPathInfo(CriteriaQueryTranslator.java:251)

I create aliases like;

criteria.createAlias("tObservation", "0").createAlias("0.raw","1").createAlias("1.waterLevel","2").addOrder(Order.asc("2.meter"))

Why I get that exception?

The above code is working for two levels eg: tObservation.id

p.s: If I try like;(without aliases)

criteria.addOrder(Order.asc("tObservation.raw.waterLevel.metre"))

I get same exception.

My class structure

@Entity
class tank {

Observation tObservation;

}


@Entity
class Observation {

@Embedded
RawObservation raw;

}

@Embeddable
class RawObservation{

    @Embedded
Length waterLevel;
}

@Embeddable
class Length{
BigDecimal metre

}

回答1:

Use something like this

Criteria cObservation = criteria.createCriteria("tObservation");
Criteria cRaw = cObservation.createCriteria("raw");
Criteria cWaterLevel = cRaw.createCriteria("waterLevel");
cWaterLevel.addOrder(Order.asc("meter"))


回答2:

You can also try like this :

Criteria cObserv = criteria.createCriteria("tObservation");
cObserv.createAlias("raw", "r");
cObserv.createAlias("r.waterLevel", "rw");

cObserv.createAlias("rw.metre", "rwm");
or
cObserv.setFetchMode("rw.metre", FetchMode.JOIN);

cObserv.addOrder(Order.asc("rw.metre"))