I'm struggling with unnecessary SQL select query when trying to get entity reference with Spring data repository using Hibernate as persistence provider.
My case concerns many times discussed question about using entityManager.getReference() in order to get proxy object with just initialized id value here and here.
But this doesn't work as described.
I have following environment and code
- Spring Boot JPA project with Hibernate
- One dead simple entity
Foo
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "d20_foo")
public class Foo {
@Id
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In my service code i'm just invoking getReference just like this
@Service
@Transactional
public class MyService {
@PersistenceContext
private EntityManager entityManager;
...
public void getFooLink() {
...
Foo foo = entityManager.getReference(Foo.class,1L);
...
}
...
}
and in hibernate logs in debug mode I see, that, once I hit getReference, following select query is performed
Hibernate:
select
foo0_.id as id1_0_0_,
foo0_.name as name2_0_0_
from
d20_foo foo0_
where
foo0_.id=?
Why is that? Why query is performed instead of just returning proxy object?
I didn't hit any additional fields (like invoking getName() on returned object) and did all as was described in reference implementations.
I don't need extra query - Foo entity is a read-only object and I need it just as a referenced object to another entity.