开发者

Add logic to a column as your querying using criteria api

I'm not even sure this is possible but I figured it's worth asking. I've been using native query's for this for a long time.

Say I have this query.

    public static List<PkgLoad> findBetweenDatesWrapSpec( PkgLine pkgLine, WrapSpec wrapSpec, Date startDate, Date endDate, boolean metric ) {

    CriteriaBuilder builder = JPA.local.get().em().getCriteriaBuilder();
    CriteriaQuery cq = builder.createQuery( PkgLoad.class );
    Root<开发者_运维知识库PkgLoad> pkgLoad = cq.from( PkgLoad.class );

    Predicate pkgLineQuery = builder.equal( pkgLoad.get( "pkgLineId" ), pkgLine );
    Predicate wrapQuery = builder.equal( pkgLoad.get( "wrapSpecId" ), wrapSpec );
    Predicate dateQuery = builder.between( pkgLoad.get( "timeStamp" ).as( Date.class ), startDate, endDate );

    cq.where( builder.and( pkgLineQuery, wrapQuery, dateQuery ) );
    cq.orderBy( builder.desc( pkgLoad.get( "timeStamp" ) ) );
    Query query = JPA.local.get().em().createQuery( cq );
    return query.getResultList();
}

I have a column called ounces in the model. What if I want to transform ounces into metric depending on a property. Now this property is dependent on the username so overriding the get method is not an option. If I override a get method it messes up the rest of the application. Just wanted to know any options for this. Thanks.


First, I see you are using Play Framework. It may be easier to use the "find" methods from Model (see here) to create the query you want.

Second, if the property depends on the user, it would eb acceptable to store a value int he Play Session when the user logs in that says if the user wants ounces or metric. That way your method only needs to check the session value via:

Scope.Session.current().get("key") //key = key for your value

and change the query accordingly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜