在Spring中配置Hibernate和單獨配置Hibernate的區別


首先說下Spring和Hibernate的幾個特征:

Spring:自動依賴注入,類都可以被當成bean使用。

Hibernate:會話工廠sessionfactory,事務管理器transaction。

如果只使用Hibernate,那么當你操作數據庫的時候,需要敲諸如:

Configuration conf = new Configuration().configure();

SessionFactory sf = conf.buildSessionFactory();

Session sess = sf.openSession();

Transaction tx = sess.beginTransaction();

然后在session里操作數據庫方法,在tx里提交。

但是當你使用Spring,在Spring里配置Hibernate時候,

首先是會話工廠可以被當作一個bean來寫入Spring配置文件當中,例如:

<bean id=”dataSource” class=”org.apache.commons.dbcp.BasicDataSource”>
<property name=”url” value=”jdbc:jtds:sqlserver://localhost:1433/test”>
</property>
<property name=”driverClassName” value=”net.sourceforge.jtds.jdbc.Driver”>
</property>
<property name=”username” value=”sa”></property>
<property name=”password” value=”123456″></property>
</bean>
<bean id=”sessionFactory” class=”org.springframework.orm.hibernate4.LocalSessionFactoryBean”>
<property name=”dataSource”>
<ref bean=”dataSource” />
</property>
<property name=”hibernateProperties”>
<props>
<prop key=”hibernate.dialect”>
org.hibernate.dialect.SQLServerDialect
</prop>
</props>
</property>
<property name=”mappingResources”>
<list>
<value>com/domain/Users.hbm.xml</value>
</list>
</property>
</bean>

在sessionfactory這個bean里配置數據源和各種屬性。當然這個類是Spring包中的,是Spring提供的功能。

然后,Spring同樣也可以以bean方式提供給Hibernate一個事務管理器,例如:

<bean id=”transactionManager”
class=”org.springframework.orm.hibernate4.HibernateTransactionManager”>
<property name=”sessionFactory” ref=”sessionFactory” />
</bean>
<tx:annotation-driven transaction-manager=”transactionManager” />

然后是事務攔截器,將事務管理器的bean注入其中,例如:

<bean id=”transactionInterceptor”
class=”org.springframework.transaction.interceptor.TransactionInterceptor”>
<!– 事務攔截器bean需要依賴注入一個事務管理器 –>
<property name=”transactionManager” ref=”transactionManager” />
</bean>

再是可以自動生成業務代理的bean,這個bean將使用事務攔截器,例如:

<!– 定義BeanNameAutoProxyCreator –>
<bean
class=”org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator”>
<!– 指定哪些bean自動生成業務代理 –>
<property name=”beanNames”>
<!– 下面是所有需要自動創建事務代理的bean –>
<list>
<value>mgr</value>
</list>
<!– 此處可增加其他需要自動創建事務代理的bean –>
</property>
<!– 下面定義BeanNameAutoProxyCreator所需的事務攔截器 –>
<property name=”interceptorNames”>
<list>
<!– 此處可增加其他新的Interceptor –>
<value>transactionInterceptor</value>
</list>
</property>
</bean>

那么,我們在其中寫的自動創建事務代理的id為mgr的bean是這樣的:

<bean id=”mgr” class=”com.service.impl.ActionManagerImpl”>
<property name=”usersDAO” ref=”usersDAO” />
</bean>

其中,usersDAO會被自動注入。

我們在usersDAO里不需要像之前要創建配置、會話工廠、事務這么復雜,只需要用getCurrentSession()下的各種方法就可以了。會幫你自動獲取當前會話。

配置起來過程會略多,但是總體寫的代碼絕對比單獨用hibernate然后在DAO類里寫的代碼要少。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM