I use Spring and Hibernate in my application and use Spring Transaction.
So, I have a service layer with @Transaction annotation for methods, and the DAO layer has methods for querying the database.
@Transactional(readOnly = false) public void get(){ }
The problem is that when I want to store the object in the database, I have to use session.flush() at the end of the DAO level method. Why?
I think that if I annotated @Transaction , then Spring should automatically commit the transaction after the service method completes.
DAO Level:
public BaseEntity saveEntity(BaseEntity entity) throws Exception { try { Session session = sessionFactory.getCurrentSession(); session.saveOrUpdate(entity); session.flush(); } catch (HibernateException he) { throw new Exception("Failed to save entity " + entity); } return entity; }
Service Level:
@Transactional(readOnly = false) public BaseEntity saveEntity(BaseEntity entity) throws Exception { return dao.saveEntity(entity); }
spring config:
<context:property-placeholder properties-ref="deployProperties" /> <tx:annotation-driven transaction-manager="transactionManager" /> <jpa:repositories base-package="com" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${app.jdbc.driverClassName}" p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}" p:acquireIncrement="5" p:idleConnectionTestPeriod="60" p:maxPoolSize="100" p:maxStatements="50" p:minPoolSize="10" /> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:persistenceXmlLocation="classpath*:META-INF/persistence.xml" p:persistenceUnitName="hibernatePersistenceUnit" p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="hibernateVendor"/> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="${hibernate.config}" p:packagesToScan="com" /> <bean id="hibernateVendor" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="false"/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory"/>
source share