Home » Java » Get EntityManager using spring manual transaction management

Get EntityManager using spring manual transaction management

Posted by: admin December 28, 2021 Leave a comment

Questions:

I have PlatformTransactionManager in dependency (JpaTransactionManager actually). I can use TransactionTemplate to perform an action in the transaction. But I can’t figure out, how do I retrieve EntityManager to use.

@Autowired PlatformTransactionManager transactionManager;

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

Here’s related configuration:

@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;
}
Answers:

There is a class called EntityManagerFactoryUtils from where you can obtain the current transaction’s entity manager based on the EntityManagerFactory you configured in your JpaTransactionManager.

For example:

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;
});

###

You can inject it with:

@PersistenceContext
private EntityManager entityManager;

###

I implemented my own simple transaction template:

@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();
        }
    }
}