问题
Related to: How to countDistinct on multiple columns
I have an entity class that contains many fields, three of which are longitude, latitude and update_time. I am trying to add a @Formula field that concatenates the three:
@Formula("concat(longitude, latitude, update_time)")
public String fix;
I would then like to use that field as part of a countDistinct query:
@SuppressWarnings( {"unchecked", "rawtypes"} )
public long getCountDistinctPositions() {
Session session = sessionFactory.openSession();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
Root<Position> position = criteriaQuery.from(Position.class);
Expression fix = position.get("fix");
Expression countDistinct = criteriaBuilder.countDistinct(fix);
criteriaQuery.select(countDistinct);
Query query = session.createQuery(criteriaQuery);
Long result = (Long)query.getSingleResult();
session.close();
return result;
}
But I keep getting an exception:
java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [fix] on this ManagedType [aaa.Position]
回答1:
A @Formula field cannot be queried, its basically a synthetic field that Hibernate will populate when a select query is executed only.
For your use case, you'd need to execute:
SELECT DISTINCT longitude, latitude, update_time FROM Entity
From a JPA query perspective, you'd need to execute #countDistinct on all 3 individual columns, not on the formula-column.
The best way to think of a formula column is that you've effectively translated the following method on your entity
@Transient
public String getFix() {
return this.longitude + this.latitude + this.update_time;
}
to a property that the database concatenates for you at query-time.
UPDATE
CriteriaQuery<Long> countQuery = cb.createQuery( Long.class );
Root<TheEntity> root = countQuery.from( TheEntity.class );
countQuery.select( cb.count( root.get( "id" ) ) );
Subquery<Integer> subQuery = countQuery.subquery( Integer.class );
Root<TheEntity> subRoot = subQuery.from( TheEntity.class );
subQuery.select( cb.min( subRoot.get( "id" ) ) );
subQuery.groupBy( subRoot.get( "longitude" ),
subRoot.get( "latitude" ),
subRoot.get( "updateTime" ) );
countQuery.where( root.get( "id" ).in( subQuery ) );
Long count = entityManager.createQuery( countQuery ).getSingleResult();
来源:https://stackoverflow.com/questions/50411647/formula-field-is-not-recognized-by-client-code