Play 框架不提供针对某一个字段求和方法,那么一般出现这种情况都会去写原生sql去执行,非常简单:
String sql = "select sum(count) as count from book ";
Long sum;
Object sumFlag = JPA.em().createNativeQuery(sql).getSingleResult();
嗯,就这样,此方法同样适合其他返回一个字段的操作
jpa获取集合(如果你想只要自己想要的字段,那么可以如下获取):
第一种:
Query query = JPA.em().createNativeQuery("select id,name,price from book");
//此段必加,指定返回的类型为Map
query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
List list = query.getResultList();
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = (Map<String, Object>) list.get(i);
System.out.println(map.get("id"));
System.out.println(map.get("name"));
System.out.println(map.get("price"));
}
第二种:
Query query = CurriVideo.em().createNativeQuery
("select "
+ "id ,"
+ "name ,"
+ "cover ,"
+ "file_path ,"
+ "charge ,"
+ "price_money ,"
+ "price_inte ,"
+ "old_price_money ,"
+ "old_price_inte ,"
+ "null as publish_date ,"
+ "null as status ,"
+ "null as curri_id ,"
+ "null as sort_num "
+ "from curri_video",CurriVideo.class);
List<CurriVideo> list = query.getResultList();
for (CurriVideo curriVideo : list) {
System.out.println(curriVideo.name);
System.out.println(curriVideo.sort_num);
}
看实际业务来决定用哪种。
个人建议第一种,第二种有局限性,比如实体中有一字段为
@OneToMany
@JoinColumn(name="curri_id")
public List<Curriculum> currList;
那么必须查询出curri_id字段,并且不能设置为空,违背了我们最初想要的结果。