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:
xxxxxxxxxx
1
// import javax.persistence.EntityManager;
2
// import javax.persistence.PersistenceContext;
3
4
5
public class SomeController {
6
7
8
private EntityManager entityManager;
9
10
// some code here ...
11
}
xxxxxxxxxx
1
package some.project;
2
3
import org.springframework.beans.factory.annotation.Autowired;
4
import org.springframework.http.MediaType;
5
import org.springframework.stereotype.Controller;
6
import org.springframework.transaction.annotation.Transactional;
7
import org.springframework.web.bind.annotation.RequestMapping;
8
import org.springframework.web.bind.annotation.RequestMethod;
9
import org.springframework.web.bind.annotation.ResponseBody;
10
11
import javax.persistence.EntityManager;
12
import javax.persistence.PersistenceContext;
13
import javax.servlet.http.HttpServletRequest;
14
15
16
public class SomeController {
17
18
19
private EntityManager entityManager;
20
21
// @Autowired
22
// private SomeRepository someRepository;
23
24
(
25
value = /path/to/some/action",
26
method = RequestMethod.GET,
27
produces = MediaType.APPLICATION_JSON_VALUE
28
)
29
30
31
public SomeResponse someAction(HttpServletRequest request) {
32
33
// some operations here ...
34
35
// SomeEntity someEntity = ...;
36
// this.entityManager.refresh(someEntity);
37
38
return new SomeResponse();
39
}
40
}