HibernateDaoSupport类的使用

来源:互联网 发布:上杭县广电网络分公司 编辑:程序博客网 时间:2024/05/16 19:22
看到一篇很好描述HibernateDaoSupport类使用的例子,特此在这和大家分享一下
 
核心提示:
1、 继承了HibernateDaoSupport类的类获取session时,已不可用SessionFactory.OpenSessioon的形式来获取Session了,由于HibernateDaoSupport本身已有获取session的方法getSession(),所以直接用Session se=this.getSession();来获取
 

              2、        在依据hql获取用户信息时,继承了HibernateDaoSupport类的类中不能在使用Query类了,而是用List<Ssh> list = this.getHibernateTemplate().find(hql);形式来获取实体类集合

实例:

Java类篇:

 

  1. import java.util.List;    
  2.   
  3. import org.hibernate.Query;   
  4.   
  5. import org.hibernate.Session;   
  6.   
  7. import org.hibernate.SessionFactory;   
  8.   
  9. import org.springframework.context.ApplicationContext;   
  10.   
  11. import org.springframework.context.support.ClassPathXmlApplicationContext;   
  12.   
  13. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;   
  14.   
  15. import entity.Ssh;    
  16.   
  17. public class SshDAO extends HibernateDaoSupport {   
  18.   
  19. //  private SessionFactory sf = null;  
  20.   
  21. //   
  22.   
  23. //  public SessionFactory getSf() {  
  24.   
  25. //     return sf;   
  26.   
  27. //  }   
  28.   
  29. //   
  30.   
  31. //  public void setSf(SessionFactory sf) {  
  32.   
  33. //     this.sf = sf;   
  34.   
  35. //  }   
  36.   
  37.     
  38.   
  39. //  public String print(int id) {  
  40.   
  41. //     Session se = sf.openSession();  
  42.   
  43. //     String hql = "from Ssh where id=" + id;  
  44.   
  45. //     Query q = se.createQuery("hql");  
  46.   
  47. //     List<Ssh> list = q.list();  
  48.   
  49. //     String a = list.get(1).getName();  
  50.   
  51. //     return a;   
  52.   
  53. //  }   
  54.   
  55.     public String print(int id) {   
  56.   
  57.        Session se =this.getSession();//获取Session对象  
  58.   
  59.        String hql = "from Ssh where id=" + id;   
  60.   
  61.        //依据hql获取实体集合,此处不要用Query类来实现  
  62.   
  63.        List<Ssh> list = this.getHibernateTemplate().find(hql);   
  64.   
  65.        String a = list.get(0).getName();   
  66.   
  67.        return a;   
  68.   
  69.     }   
  70.   
  71.     public static void main(String[] args) {   
  72.   
  73.        ApplicationContext ac=newClassPathXmlApplicationContext   
  74.   
  75. ("spring/spring.xml");   
  76.   
  77.        SshDAO ssh=(SshDAO)ac.getBean("sshD");   
  78.   
  79.        System.out.println(ssh.print(1));   
  80.   
  81.     }   
  82.   
  83. }   
原创粉丝点击