Spring多个方法的JPA事务

时间:2014-12-03 10:31:20

标签: spring jpa transactions

我在Tomcat 7中运行的Web应用程序中使用Spring 3.2和JPA以及Hibernate 4.应用程序分为控制器,服务DAO类。服务类在类和方法级别具有带注释的事务配置。 DAO是普通的JPA,实体管理器由@PersistenceContext注释注入。

@Service("galleryService")
@Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class GalleryServiceImpl implements GalleryService {

  @Override
  public Picture getPicture(Long pictureId) {
    return pictureDao.find(pictureId);
  }

  @Override
  public List<PictureComment> getComments(Picture picture) {
    List<PictureComment> comments = commentDao.findVisibleByPicture(picture);
    Collections.sort(comments, new Comment.ByCreatedOnComparator(Comment.ByCreatedOnComparator.SORT_DESCENDING));
    return comments;
  }
  ...
}

@Controller
@RequestMapping("/gallery/displayPicture.html")
public class DisplayPictureController extends AbstractGalleryController {

  @RequestMapping(method = RequestMethod.GET)
  public String doGet(ModelMap model, @RequestParam(REQUEST_PARAM_PICTURE_ID) Long pictureId) {
    Picture picture = galleryService.getPicture(pictureId);
    if (picture != null) {
      model.addAttribute("picture", picture);
      // Add comments
      model.addAttribute("comments", galleryService.getComments(picture));
    } else {
      LOGGER.warn(MessageFormat.format("Picture {0} not found.", pictureId));
      return ViewConstants.CONTENT_NOT_FOUND;
    }
    return ViewConstants.GALLERY_DISPLAY_PICTURE;
  }
  ...
}

我打开了org.springframework.transaction的调试日志记录,注意到,&#34;创建新事务&#34;,&#34;打开新的EntityManager&#34;,&#34;获取...&# 34;,&#34;结束......&#34;和#34;提交交易&#34;在我的服务类中每次调用一个方法都会完成。即使那些方法在我的控制器类中由一个单一方法调用。以下是我的日志输出示例:

2014-12-03 10:53:00,448 org.springframework.transaction.support.AbstractPlatformTransactionManager getTransaction
DEBUG: Creating new transaction with name [de.domain.webapp.gallery.service.GalleryServiceImpl.getPicture]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
2014-12-03 10:53:00,448 org.springframework.orm.jpa.JpaTransactionManager doBegin
DEBUG: Opened new EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@6133a72f] for JPA transaction
2014-12-03 10:53:00,468 org.springframework.orm.jpa.JpaTransactionManager doBegin
DEBUG: Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@5182c1b7]
2014-12-03 10:53:00,468 org.springframework.transaction.interceptor.TransactionAspectSupport prepareTransactionInfo
TRACE: Getting transaction for [de.domain.webapp.gallery.service.GalleryServiceImpl.getPicture]
2014-12-03 10:53:00,489 org.springframework.transaction.interceptor.TransactionAspectSupport commitTransactionAfterReturning
TRACE: Completing transaction for [de.domain.webapp.gallery.service.GalleryServiceImpl.getPicture]
2014-12-03 10:53:00,489 org.springframework.transaction.support.AbstractPlatformTransactionManager processCommit
DEBUG: Initiating transaction commit
2014-12-03 10:53:00,489 org.springframework.orm.jpa.JpaTransactionManager doCommit
DEBUG: Committing JPA transaction on EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@6133a72f]
2014-12-03 10:53:00,489 org.springframework.orm.jpa.JpaTransactionManager doCleanupAfterCompletion
DEBUG: Closing JPA EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@6133a72f] after transaction
2014-12-03 10:53:00,489 org.springframework.orm.jpa.EntityManagerFactoryUtils closeEntityManager
DEBUG: Closing JPA EntityManager

我知道我可以使用OpenSessionInView来保存hibernate会话以获得完整的请求,但有些人说,OSIV是一个反模式。相反,我使用的是SpringOpenEntityManagerInViewFilter。但没有成功。我怎样才能实现,Spring使用单个事务进行我的控制器的多个服务层方法调用?或者我错过了什么?

这是我的Spring配置的一部分:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="database" value="MYSQL" />
            <property name="showSql" value="false" />
        </bean>
    </property>
</bean>

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/tikron" />
</bean>

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<context:component-scan base-package="de.domain.webapp">
    <context:include-filter type="regex" expression=".*Service"/>
</context:component-scan>

我的持久单位:

<persistence-unit name="tikron-data" transaction-type="RESOURCE_LOCAL">
  <!-- Entities located in external project tikron-data -->
  <jar-file>/WEB-INF/lib/tikron-data-2.0.1-SNAPSHOT.jar</jar-file>
  <!-- Enable JPA 2 second level cache -->
  <shared-cache-mode>ALL</shared-cache-mode>
  <properties>
    <property name="hibernate.hbm2ddl.auto" value="validate" />
    <property name="hibernate.cache.use_second_level_cache" value="true" />
    <property name="hibernate.cache.use_query_cache" value="true" />
    <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
    <property name="hibernate.generate_statistics" value="false" /> 
  </properties>
</persistence-unit>

来自应用程序启动的更多日志输出:

2014-12-03 10:46:48,428 org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'tikron-data'
2014-12-03 10:46:48,428 org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
2014-12-03 10:46:48,448 org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: tikron-data
    ...]

...

2014-12-03 10:46:51,101 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6cccf90d: defining beans [propertyConfigurer,messageSource,entityManagerFactory,dataSource]; root of factory hierarchy
2014-12-03 10:46:51,111 org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 3374 ms

提前致谢。

1 个答案:

答案 0 :(得分:9)

您需要播放PROPAGATION_LEVEL并正确构建服务bean调用。如果您在服务类上使用@Transactional,那么您所描述的是正常的,因为事务划分发生在公共方法级别。因此,在进入服务bean的公共方法时,根据传播级别,事务将启动,加入现有事务,抛出异常或以非事务方式执行。

要在一个事务中执行服务方法,就足以将传播级别设置为支持 GalleryService (假设您不在方法级别覆盖它) ),并从另一个注释 @Transactional(propagation = Propagation.REQUIRED)的服务的单个方法调用这些方法。让你的电话通过一个豆子很重要,例如(galleryService.getPicture而不是本地调用getPicture),&#39;导致注入事务语义的方面对包装bean的代理工作

@Service("exampleService")
@Transactional(propagation=Propagation.REQUIRED)
public class ExampleServiceImpl implements ExampleService {

  @Autowired
  private GalleryService galleryService;

  @Override
  public void singleTransaction() {
    galleryService.getPicture
    galleryService.getComments
  }

  ...
}

简短的PROPAGATION_LEVEL词汇表

MANDATORY
          Support a current transaction, throw an exception if none exists.
NESTED
          Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
NEVER
          Execute non-transactionally, throw an exception if a transaction exists.
NOT_SUPPORTED
          Execute non-transactionally, suspend the current transaction if one exists.
REQUIRED
          Support a current transaction, create a new one if none exists.
REQUIRES_NEW
          Create a new transaction, suspend the current transaction if one exists.
SUPPORTS
          Support a current transaction, execute non-transactionally if none exists.

关于评论的更新

但是将服务方法调用组合成一个服务方法是在单个事务中处理这些调用的唯一方法吗?

不,但在我看来,这是你最好的选择。请考虑文章http://www.ibm.com/developerworks/java/library/j-ts2/index.html。我所描述的内容是文章中提到的 API层策略。它定义为

  

如果有,则使用API​​层事务策略   粗粒度方法,作为后端的主要入口点   功能。 (如果您愿意,可以将它们称为服务。)在此   场景,客户端(基于Web,基于Web服务,   基于消息,甚至是桌面)对后端进行一次调用   执行特定请求。

现在,在标准的三层体系结构中,您可以使用演示文稿,业务和持久层。简单来说,您可以注释您的控制器,服务或DAO。服务是拥有逻辑工作单元的服务。如果您注释您的控制器,它们是您的表示层的一部分,如果您的事务语义存在,并且您决定切换或添加非HTTP客户端(例如Swing客户端),您将被绑定到迁移或复制你的交易逻辑。 DAO层也不应该是事务的所有者,DAO方法的粒度远小于业务逻辑单元的粒度。我限制了最佳实践等点,但是,如果您不确定,请选择您的业务(服务)作为您的API交易层:)

你有很多帖子在各个方向讨论这个话题

why use @transactional with @service insted of with @controller Where should "@Transactional" be place Service Layer or DAO

阅读非常好,有趣,很多意见和依赖于语境的