Play框架獲取資料單個欄位與獲取部分欄位集合
阿新 • • 發佈:2018-12-26
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欄位,並且不能設定為空,違背了我們最初想要的結果。