简体   繁体   中英

Spring Hibernate only one session Factory

I am using hibernate and spring to build an application. I have many entites and therefore I implement a generic DAO, some DAO that extends this generic DAO and some services using these DAO.

public class GenericDAOImpl<T, PK extends Serializable> implements IGenericDAO<T, PK> {
private SessionFactory sessionFactory;
private Class<T> type;

public void setSessionFactory(SessionFactory sessionFactory) 
{
    this.sessionFactory = sessionFactory;
}
public Session getSession() {
    return sessionFactory.getCurrentSession();
}   
public GenericDAOImpl(Class<T> type) {
    this.type = type;
}
public void create(T o) {
    getSession().save(o);
}
@SuppressWarnings("unchecked")
public T read(PK id) {
    return (T) getSession().get(type, id);
}

public void update(T o) {
    getSession().update(o);

}

}

This is my Region DAO and and I hava also a country DAO.

  public class PaysDAOImpl extends GenericDAOImpl<Pays, String> implements IPaysDAO {


public PaysDAOImpl(Class<Pays> type) {
    super(type);

}

public void deleteRegion(Pays region) {
    // TODO Auto-generated method stub

}

 }

this my service class :

     public class RegionServiceImpl implements IRegionService {


private IRegionDAO regionDAO;


public void setRegionDAO(IRegionDAO regionDAO) {
    this.regionDAO = regionDAO;
}

public void saveRegion(Region region) {
    regionDAO.create(region);

}

public void deleteRegion(Region region) {
    // TODO Auto-generated method stub

}

  }

And finaly my main class :

   ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
   IRegionService regionBO=(IRegionService)appContext.getBean("myRegionService");
   IPaysService paysBO=(IPaysService)appContext.getBean("myPaysService");
   Region r=new Region();
   r.setNom("EUROPE");
   Pays p=new Pays();
   p.setNom("Belgique");
   p.setNomRegion(r);
   r.getLesPays().add(p);
   regionBO.saveRegion(r);
   paysBO.savePays(p);

Application context file:

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


<bean id="baselineDataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/baseline" />
    <property name="username" value="root" />
    <property name="password" value="root" />
</bean>


<bean id="baselineSessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="baselineDataSource" />
    <property name="annotatedClasses">
        <list>
            <value>domain.entites.Region </value>
            <value>domain.entites.Pays </value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="current_session_context_class">thread</prop>
        </props>
    </property>
</bean>

<!-- Hibernate Transaction Manager Definition -->
<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="baselineSessionFactory" />
</bean>


<!-- ========================= Start of DAO DEFINITIONS ========================= -->
<!-- proxy for DAO using generic DAO -->
<bean id="myGenericDAO" abstract="true">
    <property name="sessionFactory" ref="baselineSessionFactory" />
</bean>

<!-- Region DAO Definition -->
<bean id="myRegionDAO" class="dao.impl.RegionDAOImpl" parent="myGenericDAO">
    <constructor-arg value="domain.entites.Region" />
</bean>

<!-- Region DAO Definition -->
<bean id="myPaysDAO" class="dao.impl.PaysDAOImpl" parent="myGenericDAO">
    <constructor-arg value="domain.entites.Pays" />
</bean>


<!-- ========================= Start of SERVICE DEFINITIONS ========================= -->
<!-- Transactional proxy for Services -->
<bean id="proxyService"
    class="org.springframework.transaction.interceptor.TransactionInterceptor">
    <property name="transactionManager" ref="transactionManager" />
    <property name="transactionAttributes">
        <props>
            <prop key="find*">PROPAGATION_REQUIRED, readOnly</prop>
            <prop key="get*">PROPAGATION_REQUIRED, readOnly</prop>
            <prop key="*">PROPAGATION_REQUIRED, -java.lang.Exception</prop>
        </props>
    </property>
</bean>

<!-- autoproxy -->
<bean id="transactionBeanNameProxyCreator"
    class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="beanNames">
        <value>*Service</value>
    </property>
    <property name="interceptorNames">
        <list>
            <value>proxyService</value>
        </list>
    </property>
</bean>


<bean id="myRegionService" class="domain.services.impl.RegionServiceImpl">
    <property name="regionDAO" ref="myRegionDAO" />
</bean>

<bean id="myPaysService" class="domain.services.impl.PaysServiceImpl">
    <property name="paysDAO" ref="myPaysDAO" />
</bean>

My problem is that when I run my main class, and insert a region, then after a country that has a reference to this region, two sessions are created and an extra query is used as you can see here :

Hibernate: insert into REGIONS (nom_region) values (?)
Hibernate: select region_.nom_region from REGIONS region_ where region_.nom_region=?
Hibernate: insert into PAYS (nom_region, nom_pays) values (?, ?)

and when I look in my log, I saw that a first session is opened for inserting region, then closed and a second session is opened for inserting country. I would like to use one session for all my transaction. May be you can help me

That's simply because you haven't created any transactional service to create a region and a country at the same time, in the same transaction.

Instead, you'e using a first transactional service call to create the region alone, and a second one to create the country alone.

The session is bound to the transaction, and it's a good thing. You don't want the session to last forever and be filled with obsolete data from 1 hour ago. And you even less went to have a single session for all your transactions, since transactions excute in parallel, and a session is not threadsafe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM