现在的位置: 首页 > 综合 > 正文

Hibernate执行原生SQL语句的方法

2013年07月25日 ⁄ 综合 ⁄ 共 1001字 ⁄ 字号 评论关闭

如下代码:
(注意该类继承自HibernateDaoSupport ,要在applicationContext.xml中将sessionFactory注入此类中)

public class DaoUtil extends HibernateDaoSupport {

public Object executeMySQL(final String sql){
System.out.println(sql);
return getHibernateTemplate().execute( new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Connection CurConn = session.connection();
PreparedStatement ps = CurConn.prepareStatement(sql);
ps.execute();
ps.close();
session.flush();
return null;
}

} );
}

public Object executeBetchSQL(final ArrayList sqlList){
return getHibernateTemplate().execute( new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Connection CurConn = session.connection();
int count = sqlList.size();
for(int i=0;i//System.out.println(sqlList.get(i));
PreparedStatement ps = CurConn.prepareStatement(sqlList.get(i));
ps.execute();
ps.close();
session.flush();
}
return null;
}

} );
}

public static DaoUtil getFromApplicationContext(
ApplicationContext ctx) {
return (DaoUtil) ctx.getBean("DaoUtil");
}
}

抱歉!评论已关闭.