Skip to content

Instantly share code, notes, and snippets.

@nobodyiam
Last active May 25, 2017 11:45
Show Gist options
  • Save nobodyiam/da0eecbfe076f8e87349f836a8361521 to your computer and use it in GitHub Desktop.
Save nobodyiam/da0eecbfe076f8e87349f836a8361521 to your computer and use it in GitHub Desktop.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.jpa.EntityManagerFactoryAccessor;
import org.springframework.orm.jpa.EntityManagerFactoryUtils;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@Component
public class EntityManagerUtil extends EntityManagerFactoryAccessor {
private static final Logger logger = LoggerFactory.getLogger(EntityManagerUtil.class);
/**
* close the entity manager.
* Use it with caution! This is only intended for use with async request, which Spring won't
* close the entity manager until the async request is finished.
*/
public void closeEntityManager() {
EntityManagerHolder emHolder = (EntityManagerHolder)
TransactionSynchronizationManager.getResource(getEntityManagerFactory());
logger.debug("Closing JPA EntityManager in EntityManagerUtil");
EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment