I\'m building a simple Tomcat webapp that\'s using Spring Data and Hibernate. There\'s one end point that does a lot of work, so I want to offload the work to a background t
Method #1: JPA Entity Manager
In background thread: Inject entity manager or get it from Spring context or pass it as reference:
@PersistenceContext
private EntityManager entityManager;
Then create a new entity manager, to avoid using a shared one:
EntityManager em = entityManager.getEntityManagerFactory().createEntityManager();
Now you can start transaction and use Spring DAO, Repository, JPA, etc
private void save(EntityManager em) {
try
{
em.getTransaction().begin();
em.getTransaction().commit();
}
catch(Throwable th) {
em.getTransaction().rollback();
throw th;
}
}
Method #2: JdbcTemplate
In case you need low-level changes or your task is simple enough, you can do it with JDBC and queries manually:
@Autowired
private JdbcTemplate jdbcTemplate;
and then somewhere in your method:
jdbcTemplate.update("update task set `status`=? where id = ?", task.getStatus(), task.getId());
Side note: I would recommend to stay away from @Transactional unless you use JTA or rely on JpaTransactionManager.