I have an entity graph defined in my Person entity. When I declare the phone attribute as an attribute node, a join clause is created and only one select is executed, as expected. But when I remove the phone attribute from the entity graph, the phone field is still loaded, but now with a new select query for each Person retrivied. Is it possible to ignore an attribute in a particular EntityGraph?
Person Entity:
@Entity
@Table(name = "person")
@NamedEntityGraph(
name = Person.PERSON_LAZY,
attributeNodes = {}
)
public class Person {
public static final String Person_LAZY = "person.lazy";
@Id
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@JoinColumn(name = "phone")
@ManyToOne
private Phone phone;
}
PersonRepository:
@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
@EntityGraph(value = Person.PERSON_LAZY, type = EntityGraphType.FETCH)
@Query("SELECT p FROM Person p")
public List<Person> findAllLazy();
}
Short answer, no. Not possible with entity graphs or by any other means.
@ManyToOne
relations are eagerly loaded by default. You have to make it lazy to prevent it from being loaded in whatever way.
The general advice is that since you can load lazy relations eagerly, but you can't load eager relations lazily, you should favor lazy for everything just in case.
And yes, this includes entity graphs and all other possible tricks. If a relation is eager either by default or explicitly, it can never be lazy. This was apparently a design choice/implementation detail even with entity graphs, but with no plan to change it.