@Override public Goods checkGoods(Long categoryId, Long tenantId, String cardNo) { String sql = "SELECT " + " * " + "FROM " + " cce_goods " + "WHERE " + " is_deleted = 0 " + " AND goods_category_id = '" + categoryId + "' " + " AND commercial_tenant_id ='" + tenantId + "' " + " AND card_no = '" + cardNo + "'"; Query query =null; query=getSession().createSQLQuery(sql).addEntity(Goods.class); query.setParameter("0",1); query.setResultTransformer(Transformers.aliasToBean(Goods.class)); query=getSession().createQuery(sql); return (Goods) query.uniqueResult(); }
今天在作dao層操做時,一不當心寫錯了,獲得兩種狀況,一種是 query=getSession().createSQLQuery(sql).addEntity(Goods.class);和query=getSession().createQuery(sql)。也是能夠的,爲何能這樣呢?sql
查看hibernate底層源碼時發現,SQLQuery繼承Query接口,如圖所示:ide
接口的實現指向它的實現類,或者它子接口的實現類。咱們須要調用addEntity(Goods.class)增長商品類的實體類,hibernate的底層經過反射將數據填充到商品類的實例化的對象中的。可是,接口Query自己是沒有這個方法的,於是,咱們須要使用SQLQuery,而不是Query。spa
【備註】我是比較看源碼的,多看看源碼,仍是有好處的。hibernate