spring 中配置sessionFactory及用法java
方法一:mysql
一、在Spring的applicationContext.xml中配置beanspring
<!-- 啓用註解注入 -->
<context:annotation-config />
<!-- spring掃描的包 -->
<context:component-scan base-package="com.iven"/>
<!-- 配置數據源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName" value="com.MySQL.jdbc.Driver" />
<property name="url" value="jdbc:mysql://172.25.9.99:3306/fzghc" />
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置Spring的SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.iven.entity.User</value>
<value>com.iven.entity.Repairs</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
<!-- hibernate.dialect=org.hibernate.dialect.SQLServerDialect -->
hibernate.show_sql=true
</value>
</property>
</bean>
<!-- 添加事務管理 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>sql
<!-- 添加事務管理 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="queryByUsername" read-only="true"/>
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.iven.dao.*.*(..))" id="fooServiceOperation"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
</aop:config>
express
二、添加類BaseSessionFactoryImpl用於獲取Session,類BaseSessionFactoryImpl的內容以下:apache
public class BaseSessionFactoryImpl {session
@Resource(name="sessionFactory")
private SessionFactory sessionFactory=null;
public Session getSession(){
return sessionFactory.getCurrentSession();
}
}app
三、在Dao層獲取Session,url
public class UserDaoImplextends BaseSessionFactoryImpl
{spa
public User queryByUsername(String userName) {
User user=null;
String sql="select user from User user where user.userName="+userName;
try {
user=(User) getSession().get(User.class, 1);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
4.重點注意事項
SessionFactory的getCurrentSession並不能保證在沒有當前Session的狀況下會自動建立一個新的,這取決於CurrentSessionContext的實現,SessionFactory將調用CurrentSessionContext的currentSession()方法來得到Session。
在Spring中,若是咱們在沒有配置TransactionManager而且沒有事先調用SessionFactory.openSession()的狀況直接調用getCurrentSession(),那麼程序將拋出「No Session found for current thread」異常。
若是配置了TranactionManager而且經過@Transactional或者聲明的方式配置的事務邊界,那麼Spring會在開始事務以前經過AOP的方式爲當前線程建立Session,此時調用getCurrentSession()將獲得正確結果。
然而,產生以上異常的緣由在於Spring提供了本身的CurrentSessionContext實現,若是咱們不打算使用Spring,而是本身直接從hibernate.cfg.xml建立SessionFactory,而且爲在hibernate.cfg.xml
中設置current_session_context_class爲thread,也即便用了ThreadLocalSessionContext,那麼咱們在調用getCurrentSession()時,若是當前線程沒有Session存在,則會建立一個綁定到當前線程。
Hibernate在默認狀況下會使用JTASessionContext,Spring提供了本身SpringSessionContext,所以咱們不用配置current_session_context_class,當Hibernate與Spring集成時,將使用該SessionContext,故此時調用getCurrentSession()的效果徹底依賴於SpringSessionContext的實現。
在沒有Spring的狀況下使用Hibernate,若是沒有在hibernate.cfg.xml中配置current_session_context_class,有沒有JTA的話,那麼程序將拋出"No CurrentSessionContext configured!"異常。此時的解決辦法是在hibernate.cfg.xml中將current_session_context_class配置成thread。
在Spring中使用Hibernate,若是咱們配置了TransactionManager,那麼咱們就不該該調用SessionFactory的openSession()來得到Sessioin,由於這樣得到的Session並無被事務管理。
至於解決的辦法,能夠採用以下方式:
1. 在spring 配置文件中加入
<tx:annotation-driven transaction-manager="transactionManager"/>
而且在處理業務邏輯的類上採用註解
@Service public class CustomerServiceImpl implements CustomerService { @Transactional public void saveCustomer(Customer customer) { customerDaoImpl.saveCustomer(customer); } ... } 另外在 hibernate 的配置文件中,也能夠增長這樣的配置來避免這個錯誤: <property name="current_session_context_class">thread</property>