多方法上的Spring JPA事务

多方法上的Spring JPA事务,spring,jpa,transactions,Spring,Jpa,Transactions,我在运行于Tomcat7的web应用程序中使用Spring3.2和JPA以及Hibernate4。应用程序分为控制器类、服务类和DAO类。服务类在类和方法级别具有带注释的事务配置。DAO是由@PersistenceContext注释注入实体管理器的普通JPA @Service("galleryService") @Transactional(propagation=Propagation.SUPPORTS, readOnly=true) public class GalleryServiceIm

我在运行于Tomcat7的web应用程序中使用Spring3.2和JPA以及Hibernate4。应用程序分为控制器类、服务类和DAO类。服务类在类和方法级别具有带注释的事务配置。DAO是由@PersistenceContext注释注入实体管理器的普通JPA

@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;
  }
  ...
}
我知道我可以使用OpenSessionInView来保存hibernate会话以获得完整的请求,但有些人说,OSIV是一种反模式。相反,我使用的是SpringOpenEntityManagerViewFilter。但是没有成功。如何实现,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>

提前感谢。

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

要让服务方法在一个事务中执行,只需将传播级别设置为与GalleryService中相同的支持级别(前提是不在方法级别上重写它),并从另一个服务的单个方法调用这些方法,该服务的注释为@Transactional(传播=传播.REQUIRED)。让您的调用通过bean(例如(galleryService.getPicture而不是本地调用getPicture)传递是很重要的,因为注入事务语义的方面与封装bean的代理相对应

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

  @Autowired
  private GalleryService galleryService;

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

  ...
}
U级词汇表简介

关于评论的更新

但是,将服务方法调用组合到一个服务方法中是否是在单个事务中处理这些调用的唯一方法

不,但我认为这是你最好的选择。考虑一下这篇文章。我所描述的是本文中提到的API层策略。其定义为

API层事务策略在以下情况下使用: 作为后端主要入口点的粗粒度方法 功能。(如果你愿意,可以叫他们服务部。)在这里 场景,客户端(无论是基于Web的、基于Web服务的、, 基于消息,甚至是桌面)只需向后端调用 执行特定的请求

现在,在标准的三层体系结构中,您有了表示层、业务层和持久层。简单地说,您可以为控制器、服务或DAO添加注释。服务是包含逻辑工作单元的服务。如果对控制器进行注释,它们是表示层的一部分,如果存在事务语义,并且决定切换或添加非http客户端(例如Swing客户端),则必须迁移或复制事务逻辑。DAO层也不应该是事务的所有者,“DAO方法的粒度远小于业务逻辑单元的粒度。我限制了最佳实践等要点。但是,如果您不确定,请选择您的业务(服务)作为您的API事务层:)

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


非常好而且有趣的阅读,许多观点和上下文相关

谢谢您的解释!但是,将服务方法调用组合到一个服务方法中是否是在单个事务中处理这些调用的唯一方法?这将导致每个控制器有一个服务方法。我想,我的问题源于我的webapp中错误的Spring配置。编辑了一个答案,但它只是一般性的评论,而不是决定性的答案
<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
@Service("exampleService")
@Transactional(propagation=Propagation.REQUIRED)
public class ExampleServiceImpl implements ExampleService {

  @Autowired
  private GalleryService galleryService;

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

  ...
}
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.