I have a unidirectional ManyToOne relation which is declared as FetchType.lAZY , But when i query using Spring jpa repo (query dsl) findAll() , ManyToOne is eagerly loaded even if DTO layer does not access this param at all .spring.jpa.open-in-view = false. I am using Spring boot 3.(Hibernate)
Say I have Employee entity , which has say office Address as ManyToOne relation
@Entity
@Table(name = "Employee")
class Employee {
@Id
@Column
val id: String,
@ManyToOne(fetch = FetchType.LAZY)
var group: UserGroup,
/**
* The candidate that check was performed on.
*/
@ManyToOne(fetch = FetchType.LAZY)
var officeAddress: Address,
}
@Entity
@Table(name = "Address")
class Address {
@Id
@Column
val id: String,
//Other fields here
}
In the DTO layer , i am not accessing officeAddress at all ; I enabled hibernate query, I could see in the console that hibernate is firing query to fetch officeAddress when I do
@EntityGraph(attributePaths = ["group"], type = EntityGraph.EntityGraphType.FETCH)
employeeRepository.findAll(Predicate)
This entity is shared by two modules , in one module , i need just the Id of office Address in the DTO , in another I need entire officeAddress. Please note: Even if I dont access office Address at all , hibernate is still loading entire entity any way
I have tried FetchType.LAZY , which did not work, the only way how it worked was if i just say
@Column
var officeAddressId: String; But as I said I need the Address to be loaded in certain scenarios fully and in certain scenarios I just need Id without fully loading it.
Also tried adding both address Id and Address like below:
@Column(updatable=false, insertable=false)
var officeAddressId: String with
@ManyToOne(fetchType.LAZY)
var officeAddress: Address This also anyways loaded the entity whether i accessed anything or not.
nanditha b is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.