相关:How to countDistinct on multiple columns
我有一个包含许多字段的实体类,其中三个是longitude
,latitude
和update_time
。我正在尝试添加一个@Formula
字段来连接这三个字段:
@Formula("concat(longitude, latitude, update_time)")
public String fix;
然后我想将该字段用作countDistinct
查询的一部分:
@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;
}
但我一直有例外:
java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [fix] on this ManagedType [aaa.Position]
答案 0 :(得分:0)
无法查询@Formula
字段,它基本上是仅在执行选择查询时Hibernate将填充的合成字段。
对于您的用例,您需要执行:
SELECT DISTINCT longitude, latitude, update_time FROM Entity
从JPA查询的角度来看,您需要在所有3个单独的列上执行#countDistinct
,而不是在公式列上执行@Transient
public String getFix() {
return this.longitude + this.latitude + this.update_time;
}
。
考虑公式列的最佳方法是,您已在实体上有效地翻译了以下方法
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();
到查询时数据库连接的属性。
更新
# Get list of numbers
with open("/path/to/numbers.txt") as f:
content = f.read()
numbers = content.split()
# Handle each URL in a loop
for number in numbers:
url = 'http://www.example.com/%s' % number
# Do something with url