Add logic to column as query using api criteria

I'm not even sure that this is possible, but I thought it was worth asking. I have been using my own request 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 a model. What if I want to convert ounces to a metric depending on a property. This property now depends on the username, so overriding the get method is not an option. If I override the get method, it will ruin the rest of the application. Just wanted to know any options for this. Thanks.

+4
source share
1 answer

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

Secondly, if the property is user-dependent, it would be acceptable to store the int it Play Session value when the user logs in, which says that the user wants ounces or metrics. So your method should only check the session value with:

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

and modify the request accordingly.

+1
source

Source: https://habr.com/ru/post/1369031/


All Articles