Hibernate 中HibernateTemplate对象如何执行普通SQL语句

来源:互联网 发布:金山软件2017校园招聘 编辑:程序博客网 时间:2024/06/10 06:26

/**
  * HibernateTemplate执行普通sql语句;方法1
  */

 public List getViewRecordByUserAndRandom6(int userId) {
  final int userIdf = userId;
  List viewRecordList = this.getHibernateTemplate().executeFind(
    new HibernateCallback() {
     public Object doInHibernate(Session session)
       throws HibernateException, SQLException {
      SQLQuery query = session
        .createSQLQuery("select * from viewrecord where userId=? order by rand() limit 6");
      query.setInteger(0, userIdf);
      return query.list();
     }
    });
  return viewRecordList;
 }
 
 /**
  * 或者使用一下方法 getSession();方法2
  * @param userId
  * @return
  */

 public List getViewRecordByUserAndRandom7(int userId) {
  String sql = "select * from viewrecord where userId=? order by rand() limit 6";
  Session session = this.getSession();
  List viewRecordList = session.createSQLQuery(sql).list();
  return viewRecordList;
 }
 
 /**
  * 使用底层JDBC执行;方法三
  */
 //获取一个Connection

 Connection conn = getHibernateTemplate().getSessionFactory().openSession().connection();
 Statement st=conn.createStatement();
 st.execute("select * from tablename");
 //最后关闭链接
 finally{
    try{
     if(st!=null)
      st.close();
     if(conn!=null)
      conn.close();
    }catch(SQLException e){
     System.out.println(e.toString());
    }
   }

原创粉丝点击