5

Answers like https://stackoverflow.com/a/12828955/3395716 and https://stackoverflow.com/a/32184186/3395716 and many others mention of some enitityManager.getReference() method, which can be used to avoid making unnecessary select queries to the database.

I am having similar issue in spring boot app, when trying to save an object to the database, using CRUDRepository. My class looks like,

class StudentSubject {
    String studentId;
    @ManyToOne
    private Subject subject;
    @ManyToOne
    private Student student;
}

I have to unnecessarily make find() calls to get the student and subject objects from the database, only to pass them to StudentSubjectRepository to save() them. But I already have the primary keys of both subject and student. So I would like to use them instead, and entityManager looks like what I need.

But I have no idea where this entityManager comes from, or if there is any equivalent to it in Spring Boot.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
Registered User
  • 2,239
  • 3
  • 32
  • 58

2 Answers2

8

If you use JpaRepository interface for your repository instead of CRUDRepository, you will gain access to getOne(id) method which is the equivalent of the entityManager.getReference.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
  • 1
    Not really, in general a Controller should know as least as possible about the low-level retrieval of data from the database i.e. entityManager. The usage of specialized repositories adds another abstraction layer which in testing , can easily mocked and injected. – Maciej Kowalski Jan 15 '18 at 14:06
5

It's injected normally, Spring Boot has nothing to do with it (Spring Boot is just Spring albeit with some configuration differences).

Just add

@PersistenceContext
private EntityManager em;

to your class and you can access the raw EntityManager object and all that it offers. There's nothing wrong with using it, you can't get everything done with repositories.

Kayaman
  • 72,141
  • 5
  • 83
  • 121