HibernateDaoSupport类的使用

看到一篇很好描述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. }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值