使用spring手动事务管理获取EntityManager

时间:2014-12-03 11:40:05

标签: java spring jpa transactions

我依赖PlatformTransactionManager(实际上是JpaTransactionManager)。我可以使用TransactionTemplate在事务中执行操作。但我无法弄清楚,如何检索要使用的EntityManager。

@Autowired PlatformTransactionManager transactionManager;

void doSomething() {
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            EntityManager entityManager = ???;
            // do work
        }
    });
}

以下相关配置:

@Bean
public DataSource dataSource() { ... }

@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactory.setDataSource(dataSource());
    ...
    return entityManagerFactory;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
    jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);
    return jpaTransactionManager;
}

3 个答案:

答案 0 :(得分:4)

有一个名为EntityManagerFactoryUtils的课程,您可以根据EntityManagerFactory中配置的JpaTransactionManager获取当前交易的实体管理员。

例如:

JpaTransactionManager tm = context.getBean(JpaTransactionManager.class);
EntityManagerFactory emf = tm.getEntityManagerFactory();

TransactionTemplate template = new TransactionTemplate(tm);
template.execute(status -> {
    EntityManager em = EntityManagerFactoryUtils.getTransactionalEntityManager(emf);
    Department department = new Department();
    department.setId(15);
    department.setName("Engineering");
    em.persist(department);
    return department;
});

答案 1 :(得分:1)

你可以注入:

@PersistenceContext
private EntityManager entityManager;

答案 2 :(得分:0)

我实现了自己的简单交易模板:

@Component
public class JpaTransactionTemplate {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    public void execute(Consumer<EntityManager> consumer) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            EntityTransaction transaction = entityManager.getTransaction();
            transaction.begin();
            try {
                consumer.accept(entityManager);
                transaction.commit();
            } catch (RuntimeException e) {
                try {
                    transaction.rollback();
                } catch (Exception rollbackException) {
                    e.addSuppressed(rollbackException);
                }
                throw e;
            }
        } finally {
            entityManager.close();
        }
    }
}