使用hibernate执行sql语句

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;
		}
	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值