/**
* 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());
}
}