Spring3 整合 Hibernate4- 注入SessionFactory
版本:
spring-framework-3.2.4.RELEASE hibernate-release-4.2.5.Finaljdk1.7
要使用Spring3整合Hibernate4需要再添加以下包
1.—- spring-orm-3.2.4.RELEASE.jar 2.—- spring-dao-2.0.7.jar(Spring里没有提供,,需要到网上下载)
在要用到hibernate的类中添加SessionFactory属性和相应的set方法
public class StudentDaoImpl implements IStudentDao { SessionFactory sessionFactory;public void save(Student student) {Session session = sessionFactory.getCurrentSession();session.beginTransaction();session.save(student);session.getTransaction().commit();System.out.println(“save:”+student.getName());} setSessionFactory(SessionFactory sessionFactory) {this.sessionFactory = sessionFactory;}}
在配置文件中添加SessionFactory 的baen
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xsi:schemaLocation=”http://www.springframework.org/schema/beans”
————————————————————————————————————
使用数据源(DataSource)
如果要使用数据源:
1.先把数据源相关的包导入到项目。
2.在Spring配置文件中添加数据源的bean。
3.把数据源 bean 注入到sessionFactory的dataSource属性。
(关于 Spring 注入数据源:)
Spring配置文件 如下:
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xsi:schemaLocation=”http://www.springframework.org/schema/beans”
现在数据库连接交由数据源来管理。可以把 hibernate.cfg.xml 文件中的connection.driver_class、connection.username等属性去掉了。
————————————————————————————————————–
去掉Hibernate配置文件
通过注入的方式为SessionFactory注入hibernate的配置信息,从而省去hibernate配置文件
Spring配置文件 如下:
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xsi:schemaLocation=”http://www.springframework.org/schema/beans”truethreadorg.hibernate.dialect.Oracle10gDialectcom/startspring/entrty/Student.hbm.xml
现在可以把 hibernate.cfg.xml 文件删除了。
原来Spring的配置文件中<property value=”classpath:hibernate.cfg.xml”/>这行代码也可以删去了。
———————————————————————————————————-
Spring2.X版本整合Hibernate
Spring2.x整合Hibernate和Spring3.x版基本一致,但要注意以下几点:
1. Spring2.x只支持Hibernate3 ,并不支持Hibernate4
2. 整合 Hibernate3 使用的SessionFactory Bean 是:org.springframework.orm.hibernate3包下的LocalSessionFactoryBean而不是org.springframework.orm.hibernate4.LocalSessionFactoryBean(Spring3整合hibernate3也是)
3. 导入包时注意删除相同的包!(优先删除版本低的)
既有美妙的风景,也会有称不上景只有风的地方。