ssh项目如何在普通类中调用sessionFactory进行对数据库的操作

一般的ssh项目都是按照action-->service-->dao进行页面与数据库的交互,而项目里如果建一个普通类该如何对数据库进行操作呢?

代码如下:

public void xxx(){
  ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
  SessionFactory sessionFactory = (SessionFactory)ac.getBean("SessionFactory");
  Session session =sessionFactory.openSession();
  Query q = session.createQuery(sql语句);
       ...
}

beans.xml是命名各种bean的文件,SessionFactory是bean.xml中配置数据源的那个bean的id(我的是<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">),

得到session后就可以创建sql语句进行对数据的增删改查。

 

posted @ 2015-07-01 13:21  LyzRecord  阅读(594)  评论(0编辑  收藏  举报