hibernate 执行原生sql的几种方式

hibernate 执行原生sql的几种方式

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.dto.Role;


public class HibernateTest1 {
	 public static void main(String[] args) {
	        SessionFactory sf = new Configuration().configure().buildSessionFactory();
	        Session s = null;
	        Transaction t = null;

	        try{
	            s = sf.openSession();
	            t = s.beginTransaction();

	            String sql = "SELECT id,rolename,createtime FROM sys_role"; 
	            SQLQuery query = s.createSQLQuery(sql); 
	            //方式1 error
//	            List<Object[]> list = query.list();  
	            
	           //方式2
//	            query.addScalar("id",Hibernate.INTEGER); 
//	            query.addScalar("rolename",Hibernate.STRING); 
//	            query.addScalar("createtime",Hibernate.DATE); 
//	            List<Object[]> list = query.list(); 
	            //方式3 需要对应映射的实体
	            query.addEntity(Role.class); 
	            List<Role> list = query.list(); 
	            
	            //方式4 需要hibernate版本> hibernate3.2
//	            query.addScalar("id",Hibernate.INTEGER); 
//	            query.addScalar("rolename",Hibernate.STRING); 
//	            query.addScalar("createtime",Hibernate.DATE);
//	            query.setResultTransformer(Transformers.aliasToBean(Role.class)); 
//	            List<Role[]> list = query.list(); 
	            
	            t.commit();
	       }catch(Exception err){
	            t.rollback();
	            err.printStackTrace();
	      }finally{
	            s.close();
	      }
	    }
}


参考http://bhdweb.iteye.com/blog/801084
http://www.cnblogs.com/redant/archive/2010/01/28/1658479.html
http://www.blogjava.net/yxhxj2006/archive/2012/06/30/381861.html

你可能感兴趣的:(Hibernate)