How do I properly do a background thread when using Spring Data and Hibernate?

后端 未结 3 738
小鲜肉
小鲜肉 2020-11-28 11:00

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

3条回答
  •  粉色の甜心
    2020-11-28 11:23

    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.

提交回复
热议问题