EN
Spring Boot - access to JPA EntityManager in controller (@Autowired)
25
points
In this short article, we would like to show how to get access to JPA EntityManager in a controller in Spring Boot project.
Instead of @Autowired
annotation, we should use @PersistenceContext
annotation.
Quick solution:
// import javax.persistence.EntityManager;
// import javax.persistence.PersistenceContext;
@Controller
public class SomeController {
@PersistenceContext
private EntityManager entityManager;
// some code here ...
}
Practical example
package some.project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
@Controller
public class SomeController {
@PersistenceContext
private EntityManager entityManager;
// @Autowired
// private SomeRepository someRepository;
@RequestMapping(
value = /path/to/some/action",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseBody
@Transactional
public SomeResponse someAction(HttpServletRequest request) {
// some operations here ...
// SomeEntity someEntity = ...;
// this.entityManager.refresh(someEntity);
return new SomeResponse();
}
}