How to resolve QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list

I am using spring data jpa and Specification (code was made in Kotlin)
My entities:

class ClientGroup(

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "most_profitable_sales")
val mostProfitableSales: User?,

@OneToOne(fetch = FetchType.LAZY, mappedBy = "group")
override val action: ClientGroupActionSub? = null

)

class User(

@Column(name = UserColumn.ID)
Id val id: String,

@Column(name = UserColumn.EMAIL)
val email: String? = null,
)

class ClientGroupActionSub(

@Id
val id: Long,

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "client_id")
val client: Client,

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "group_id")
val group: ClientGroup,

)

my repository:

interface ClientGroupRepository : JpaRepository<ClientGroup, Long>, JpaSpecificationExecutor

I call findAll with the following specification

Specification { root, query, cb →
root.fetch<ClientGroup, User>(ClientGroup_.MOST_PROFITABLE_SALES, JoinType.LEFT)
root.fetch<ClientGroup, ClientGroupActionSub>(ClientGroup_.ACTION, JoinType.LEFT)
cb.and()
}

and obtained the error

org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=generatedAlias1,role=com.model.ClientGroup.mostProfitableSales,tableName=users,tableAlias=user1_,origin=client_group clientgrou0_,columns={clientgrou0_.most_profitable_sales,className=com.model.User}}] [select count(generatedAlias0) from com.model.ClientGroup as generatedAlias0 left join fetch generatedAlias0.mostProfitableSales as generatedAlias1 left join fetch generatedAlias0.action as generatedAlias2 where 1=1]; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=generatedAlias1,role=com.ClientGroup.mostProfitableSales,tableName=users,tableAlias=user1_,origin=client_group clientgrou0_,columns={clientgrou0_.most_profitable_sales,className=com.model.User}}] [select count(generatedAlias0) from com.model.ClientGroup as generatedAlias0 left join fetch generatedAlias0.mostProfitableSales as generatedAlias1 left join fetch generatedAlias0.action as generatedAlias2 where 1=1]

NB: I tried to use join instead of fetch. It’s works by doesn’t solve n+1 problem that I tried to solve here

I recently had this issue and this query solved it
@Query(
value = “FROM TableName t LEFT JOIN FETCH t.columnName WHERE t.columnName = value”,
countQuery = “select count(t) from TableName t left join t.columnName WHERE t.columnName = value”)

Note the where clause can be removed to you don’t have what you are filtering by.