Reputation: 2299
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.
Upvotes: 5
Views: 2367
Reputation: 26572
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
.
Upvotes: 8
Reputation: 73578
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.
Upvotes: 5