Languages
[Edit]
EN

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

25 points
Created by:
Root-ssh
97450

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();
    }
}

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.

❤️💻 🙂

Join