發表於 程式分享

hibernate 5.0 vs. 5.2.8 對於native sql的寫法差異

將程式由hibernate 5.0升級至hibernate 5.2.8一直卡在WHERE條件用in時,查詢結果會出現非此table object之錯誤訊息,但未加in條件時又正常。
試出來5.0有addEntity method指定table object,但5.2.8除了要用TypedQuery指定型別外,於createNativeQuery方法的第二個參數還要指定此table object(class),以下列出兩個版本對native sql的差異。

一、hibernate 5.0

String sHql = "SELECT t1.* " +
                    "  FROM JBContact t1 " +
                    " WHERE t1.cKind = :NotifyType " +
                    "   AND t1.userId in (SELECT empId " +
                    "                  FROM PREmp t22 " + 
                    "                  WHERE platForm = :PlatForm  " +
                    "                   AND funcId   = :FuncId  " +
                    "                   AND cmdId    = :CmdId  " +
                    "                   AND cmdEnable=1)";

SQLQuery query = session.createSQLQuery(sHql);
query.addEntity(JBContact.class);
           
query.setParameter("NotifyType", notifyType.getCode());
query.setParameter("PlatForm", platForm);
query.setParameter("FuncId", funcId);
query.setParameter("CmdId", cmdId.toString());

List<JBContact> jbContactList = query.list();

二、hibernate 5.2.8

String sHql = "SELECT t1.* " +
                    "  FROM JBContact t1 " +
                    " WHERE t1.cKind = :NotifyType " +
                    "   AND t1.userId in (SELECT empId " +
                    "                  FROM PREmp t22 " + 
                    "                  WHERE platForm = :PlatForm  " +
                    "                   AND funcId   = :FuncId  " +
                    "                   AND cmdId    = :CmdId  " +
                    "                   AND cmdEnable=1)";
       
TypedQuery<JBContact> query = session.createNativeQuery(sHql, JBContact.class);

query.setParameter("NotifyType", notifyType.getCode());
query.setParameter("PlatForm", platForm);
query.setParameter("FuncId", funcId);
query.setParameter("CmdId", cmdId.toString());
           
List<JBContact> jbContactList = query.getResultList();