我有一个基于Spring的应用程序,它有一个后台轮询服务在一个单独的线程中运行,以更新数据库(EmployeeStatusPollService
)中的数据状态。我使用JPA(Hibernate供应商)作为存储库。我在两个解决方案中实现了这项服务,但只有一个解决方案有效以下是两种解决方案。
解决方案1:其他服务类和投票服务中的事务方法checkAndUpdateStatus
将其调用
@Service
public class EmployeeStatusPollService implements Runnable {
@Inject
private EmployeeService employeeService;
private static final int DEFAULT_PAGE_SIZE = 300;
private boolean flag = true;
public EmployeeStatusPollService() {
}
@PostConstruct
public void start() {
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
executor.setConcurrencyLimit(SimpleAsyncTaskExecutor.NO_CONCURRENCY);
executor.execute(this);
}
public void run() {
while(flag) {
try {
int pagenum = 1;
List<Employee> items = null;
do {
items = employeeService.checkAndUpdateStatus(pagenum, DEFAULT_PAGE_SIZE);
} while(items != null && items.size() == DEFAULT_PAGE_SIZE);
} catch(Exception ex) {
}
}
}
}
@Service
public class EmployeeServiceImpl implements EmployeeService {
private static final Logger LOG = LoggerFactory.getLogger(EmployeeServiceImpl.class);
@Inject
private EmployeeRepository employeeRepository;
@Transactional
public List<Employee> checkAndUpdateStatus(int pagenum, int pagesize) throws Exception {
// ....
}
}
解决方案2:交易方法checkAndUpdateStatus
处于轮询服务类
@Service
public class EmployeeStatusPollService implements Runnable {
@Inject
private EmployeeRepository employeeRepository;
private static final int DEFAULT_PAGE_SIZE = 300;
private boolean flag = true;
public EmployeeStatusPollService() {
}
@PostConstruct
public void start() {
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
executor.setConcurrencyLimit(SimpleAsyncTaskExecutor.NO_CONCURRENCY);
executor.execute(this);
}
public void run() {
while(flag) {
try {
int pagenum = 1;
List<Employee> items = null;
do {
items = checkAndUpdateStatus(pagenum, DEFAULT_PAGE_SIZE);
} while(items != null && items.size() == DEFAULT_PAGE_SIZE);
} catch(Exception ex) {
}
}
}
@Transactional
public List<Employee> checkAndUpdateStatus(int pagenum, int pagesize) throws Exception {
// ....
}
}
方法checkAndUpdateStatus
@Transactional
public List<Employee> checkAndUpdateStatus(int pagenum, int pagesize) throws Exception {
PageRequest page = new PageRequest(pagenum, pagesize);
Page<Employee> pagedItems = employeeRepository.findByStatus(EmployeeStatus.PENDING, page); // Line 1: Query employees
List<Employee> emps = pagedItems.getContent();
List<Long> updatedItems = new ArrayList<>();
int i = 0;
for(Employee emp:emps) {
try {
// ...
emp.setStatus(status); // Line 2: Update employee's status
employeeRepository.save(emp); // Line 3: Save/Update employee
updatedItems.add(emp.getId());
i++;
if(i % 50 == 0) {
employeeRepository.flush(); // Line 4: flush for every 50 employees
}
//....
} catch (Exception ex) {
// handle exception here....
}
}
return emps;
}
配置
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="jpaDialect" ref="jpaDialect"></property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"></property>
<property name="packagesToScan" value="${jpa.packagesToScan}" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop>
<prop key="hibernate.connection.defaultAutoCommit">${hibernate.connection.defaultAutoCommit}</prop>
</props>
</property>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"></bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
解决方案2不起作用,当它在方法checkAndUpdateStatus
的第3行更新/保存实体到数据库时,我收到错误“持久化实体已分离...”。
IMO,解决方案2不起作用,因为方法checkAndUpdateStatus
没有被放入事务上下文中,尽管它被@Transactional
标记。即使我设置REQUIRES_NEW
它仍然无效。任何人都可以解释这个错误为什么会发生或给我一些关于此的参考文档?
答案 0 :(得分:7)
事务性注释通过在原始类上创建代理来工作,对类中方法的本地或内部调用不会导致调用代理方法。换句话说,从类中的方法到同一类中的另一个方法的调用不会被代理拦截。
在您的情况下具体说明:
要使事务注释起作用,spring会围绕EmployeeStatusPollService类创建一个代理,它将包装您的EmployeeStatusPollService类实例,以拦截对具有事务注释的checkAndUpdateStatus方法的调用。
checkAndUpdateStatus方法的代理版本添加了所需的事务行为,然后调用原始的checkAndUpdateStatus方法。但是,这会产生这样的效果:在类实例中对checkAndUpdateStatus方法的任何调用都直接在该实例上调用,并且不会被包装代理拦截。
因此,在第二个示例中,当从EmployeeStatusPollService的另一个方法内部调用“checkAndUpdateStatus”时,不会在具有事务功能的EmployeeStatusPollService的代理版本上调用它,而是在正常版本上调用它。
第一个例子有效,因为checkAndUpdateStatus位于不同的类中,因此外部调用被代理拦截。
您可以在此处详细了解事务处理与代理的创建有关的事实: https://spring.io/blog/2012/05/23/transactions-caching-and-aop-understanding-proxy-usage-in-spring
您可以在此处阅读有关代理过程如何工作的信息: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-understanding-aop-proxies