竞彩篮球比分直播360彩票:Hibernate里使用JDBC查詢示例代碼

jopen 7年前發布 | 21K 次閱讀 Hibernate 持久層框架

篮球比分188直播 www.703192.live 在使用hibernate的時候,有的時候需要用sql語句來執行,而HibernateDaoSupport方便了操作后,執行sql時候遇到不能執行的問題,   

下列方法是一個內部類來執行sql,可以寫一個通用方法來執行sql,通常如果沒有必要盡量不使用sql,但是有的時候就必須使用了,就想下列的查詢分組查詢,不想在hibernate中使用一對多關系,而又必須使用group by 哪么只能使用下列方式

import org.hibernate.HibernateException;      
import org.hibernate.Session;      
import org.springframework.orm.hibernate3.HibernateCallback;      
import java.sql.SQLException;      
import java.sql.Connection;      
import java.sql.PreparedStatement;      
import java.sql.ResultSet;      

public List<KnowledgeQueryBean> getKnowledgeQueryInfo() {      
         List<KnowledgeQueryBean> ListAll = new ArrayList<KnowledgeQueryBean>();      
        final String sql = "SELECT   ky.KNOWLEDGEQUERYID,ky.TITILE,ky.CREATEDATE,eu.USERNAME ,ky.USERID,COUNT(kyr.KNOWLEDGEQUERYID) AS COUNT"+      
                " FROM   KNOWLEDGEQUERY ky LEFT JOIN KNOWLEDGEQUERYANSWER kyr ON   ky.KNOWLEDGEQUERYID =   kyr.KNOWLEDGEQUERYID" +      
                " LEFT JOIN EOM_USER eu   ON ky.USERID = eu.USER_ID"+      
                " GROUP BY ky.KNOWLEDGEQUERYID,ky.TITILE,ky.CREATEDATE,eu.USERNAME,ky.USERID ORDER BY ky.CREATEDATE DESC";      
         ListAll = (List<KnowledgeQueryBean>)this.getHibernateTemplate().execute(      
                new HibernateCallback(){      
                    public Object doInHibernate(Session session)      
                    throws HibernateException, SQLException {      
                     Connection con = session.connection();      
                     PreparedStatement ps = con.prepareStatement(sql);      
                     ResultSet rs = ps.executeQuery();      
                     List<KnowledgeQueryBean> all = new ArrayList<KnowledgeQueryBean>();      
                    while(rs.next()){      
                         KnowledgeQueryBean kqb = new KnowledgeQueryBean();      
                         kqb.setKnowledgeQueryId( rs.getLong("KNOWLEDGEQUERYID"));      
                         kqb.setTitle(rs.getString("TITILE"));      
                         kqb.setCreateDate(rs.getDate("CREATEDATE"));      
                         kqb.setContent(rs.getString("USERNAME"));      
                         kqb.setUserId(rs.getLong("USERID"));      
                         kqb.setCount(rs.getInt("COUNT"));      
                         all.add(kqb);      
                     }      
                     rs.close();      
                     ps.close();      
                     session.flush();      
                     session.close();      
                    return all;      
                     }      
                 }      
         );      
        return ListAll;      
     }
地址://blog.csdn.net/fei1502816/article/details/7198213

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!