Spring Boot - access to JPA EntityManager in controller (@Autowired)

25 points
Created by:

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;

public class SomeController {

    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;

public class SomeController {

    private EntityManager entityManager;

    // @Autowired
    // private SomeRepository someRepository;

            value = /path/to/some/action",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE
    public SomeResponse someAction(HttpServletRequest request) {

        // some operations here ...

        // SomeEntity someEntity = ...;
        // this.entityManager.refresh(someEntity);

        return new SomeResponse();

Alternative titles

  1. Spring Boot - access to JPA entity manager in controller (@Autowired)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Spring Boot

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂