1.如果只执行查询,可以使用,session的createSQLQuery方法。
2.执行其他操作,如insert、 delete,可以使用以下格式
public int insertValue( int pid,String vcode,String vvalue,String state,String mname){ Session session = null ; Transaction tr = null ; Connection con = null ; PreparedStatement ps = null ; try { if (pid> 0 &&vcode!= null &&vvalue!= null &&mname!= null ){ session = getSession(); String sql = "insert into sf_3_clinic(pid," +vcode+ ") values(" +pid+ "," +vvalue+ ")" ; session = getHibernateTemplate().getSessionFactory().openSession(); tr = session.beginTransaction(); con = session.connection(); ps = con.prepareStatement(sql); ps.executeUpdate(); tr.commit(); session.close(); con.close(); ps.close(); return 1 ; } return 0 ; } catch (Exception e){ e.printStackTrace(); return 0 ; }}3.今天用了一下session.connection();deprecated了,好吧换个方法吧,API中有这么一段话(scheduled for removal in 4.x). Replacement depends on need; for doing direct JDBC stuff use doWork(org.hibernate.jdbc.Work); for opening a 'temporary Session' use (TBD),好吧,定义一个类实现work接口,(本来打算使用匿名类,但是匿名类都忘了怎么写,就只有放弃了,下午有空在看看匿名类的写法)实现execute方法,给实现类了一个构造函数用于传一些参数。
package util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.hibernate.jdbc.Work;
public class DeleteNewsWork implements Work {
private String newsids;
public DeleteNewsWork(String newsids){
this.newsids=newsids;
}
public void execute(Connection connection) throws SQLException {
// TODO Auto-generated method stub
PreparedStatement stmt = connection
.prepareStatement("delete from news where newsId in ("+newsids.toString()+")");
stmt.executeUpdate();
}
}在程序中这样使用DeleteNewsWork,
//删除消息
public void deleteNews(String[] newsids){ log.debug("deleteNews"); try { Session session = null; if (newsids != null && newsids.length > 0) { String parameter=""; for( String s:newsids){ parameter+=s+","; } parameter=parameter.subSequence(0,parameter.length()-1).toString();//去掉最后一个逗号 System.out.println(parameter); session = getSession(); Transaction tx = session.beginTransaction(); // 定义一个匿名类,实现了Work接口 DeleteNewsWork work=new DeleteNewsWork(parameter); session.doWork(work); tx.commit(); } } catch (RuntimeException re) { log.error("get failed", re); throw re; } }
版权声明:本文为zd10101501原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。