如何用hibernate直接進行SQL語句查詢
我寫個簡單的例子,樓主可以參考下public int getLogin(String username,String password) { String sql="select * from user_table where username=? and password=?"; SQLQuery query=getSession().createSQLQuery(sql).addEntity(*); *ing(0,username); *ing(1,password); return *nt(*Result().toString()); } public static void main(String[] args) { new UserTableDAO().getLogin("zhang","yuan"); }。
如何用hibernate直接進行SQL語句查詢
我寫個簡單的例子,樓主可以參考下public int getLogin(String username,String password)
{ String sql="select * from user_table where username=? and password=?";
SQLQuery query=getSession().createSQLQuery(sql).addEntity(*);
*ing(0,username);
*ing(1,password);
return *nt(*Result().toString());
}
public static void main(String[] args) {
new UserTableDAO().getLogin("zhang","yuan");
}
hibernate sql查詢語句
既然你的項目繼承了hibernateDaoSupoort,并且是由spring來管理的那么,我想應該實在*中配置的sessionFactory或者getTemplate來注入數據庫連接的,既然如此在hibernateDaoSupport的繼承類中可以得到寫很多的封裝查詢、添加、刪除操作,只需要把方法加入一個抽象類去實現就好了
不過你要通過sql語句去實現的話
因為已經注入了數據庫連接到hibernateDaoSupport中.所以你也繼承到了兩個數據庫連接方法getSession() 和 getHibernateTemplate()
直接用就可以了
HIBERNATE怎樣查看sql語句
弄hibernate時,想顯示sql語句,可以設置show_sql為true來達到這個目的,但是參數值全是像PreparedStatement一樣,用?來代替的。
用p6spy可以達到顯示的那些參數原值的目的,但可讀性差。可以利用SQL Profiler來處理這個事情。
p6spy:
SQL Profile:
p6spy安裝:
* 將*放到WEB-INF/lib目錄下,將*ties放到WEB-INF/classes目錄下。
* 修改你 原有 JDBC Driver為:*.P6SpyDriver
* 修改 *ties 中的 realdriver 值為 原有 的JDBC Driver,比如我的是:*
* 完成,運行web server。
我的日志記錄產生在 %TOMCAT_HOME%\bin下,此log位置可以能過修改 logfile = x:\x_dir\* 來控制
打開看看,看里面的日志是不是看起來比較不爽?下面我們安裝SQL Profiler來讓自已的視線爽一點。
SQL Profiler安裝:(須p6spy成功安裝)
* 將SQL Profiler自帶的*ties覆蓋原來的classes目錄下文件
* 修改現在*ties中realdriver 值為 原有 的JDBC Driver
看后看看readme注意這幾句 ^__^ :
1. Start the GUI
2. Start the webapp, in starts doing some JDBC requests we will ignore
3. Press the "reset" button on the GUI
4. Make a request to the webapp
5. Press the "pause" button after the request has finished executing
6. Press the "report" button to save profiling results as a CSV file
* 我們先用java -jar * 運行 sql profiler
* 然后啟動web server :-)
一切盡在眼前了吧?
hibernate對SQL語句的使用
如下代碼:
(注意該類繼承自HibernateDaoSupport ,要在*中將sessionFactory注入此類中)
public class DaoUtil extends HibernateDaoSupport {
public Object executeMySQL(final String sql){
*n(sql);
return getHibernateTemplate().execute( new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Connection CurConn = *tion();
PreparedStatement ps = *eStatement(sql);
*e();
*();
*();
return null;
}
} );
}
public Object executeBetchSQL(final ArrayList sqlList){
return getHibernateTemplate().execute( new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Connection CurConn = *tion();
int count = *();
for(int i=0;i//*n(*(i));
PreparedStatement ps = *eStatement(*(i));
*e();
*();
*();
}
return null;
}
} );
}
public static DaoUtil getFromApplicationContext(
ApplicationContext ctx) {
return (DaoUtil) *n("DaoUtil");
}
}
轉載請注明出處華閱文章網 » hibernate的sql查詢語句