Frage

I'm using java 1.6 and spring 3.0.4, I want to realize a java functionality that

  • calculate new data values
  • update one-by-one the existing values on the database

If in any of this step there's an error I want to rollback the whole transaction and come back to the previous state.

I already realized all this pieces of code, I just want to put them together. How I can manage this with the existing spring values that are working with @Entity and @Column annotations?

Thanks!

War es hilfreich?

Lösung 2

For people that need the same configuration, here you can find how I solved this problem, integrating Hibernate with Spring.

<!-- session factory activate the transaction modules for the specified classes -->
<bean id="sessionFactory"  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
  <ref bean="dataSource" />
</property>
<property name="configLocation" value="classpath:config-hibernate.xml" />
<property name="packagesToScan">
  <list>
    <!-- Additional packages required to be added if entities located elsewhere -->
    <value>com.some.package.dao</value>
    <value>com.some.package.model</value>
    <value>com.some.package.SpecificClass</value>
  </list>
</property>
<property name="mappingResources" ref="mappingResources"/>

<bean id="mappingResources" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
  <list>
    <!-- here you can add your hibernate mapping query that you want to use on transaction -->
    <value>config-hibernate-mapping.xml</value>
  </list>
 </property>
</bean>

<!-- This will activate transactional annotation -->
<tx:annotation-driven transaction-manager="transactionManager" />

@Service
@Transactional
public class SpecificClass {
  // write your method, everyone of them will be transactional
  // and there will be  a commit in case of success or rollback in case of exception
} 

Andere Tipps

Short answer: as you're using Spring, the easiest would be to use the transaction management, creating a service that represents this transaction unit and annotate the method with @Transactional

In practice, you need to configure a PlatformTransactionManager in your application. As you seem to use JPA, the JpaTransationManager seems like an obvious choice. To enable the processing of the @Transactional annotation, you can either use @EnableTransactionManagement or the <tx:annotation-driven/> namespace. Both are explained in the Javadoc of @EnableTransactionManagement

By default, a runtime exception thrown from that annotated method will manage a transaction rollback. If your code is using checked exceptions, you'll have to configure the rollbackFor attribute of the annotation.

There are more details and examples available in the documentation

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top