I have two kotlin Entities, currently with the N+1 query problem for the OneToMany annotation.
@Entity
@NamedEntityGraph(
name = "ParentEntity.children",
attributeNodes = [NamedAttributeNode("children")]
)
class ParentEntity(
@Id
@GeneratedValue(generator = "uuid2")
val id: UUID? = null,
val name: String
): Serializable {
@Column(name = "secondaryId", columnDefinition = "bigserial", insertable = false, updatable = false)
@Generated(GenerationTime.INSERT)
var secondaryId: Long = null
@OneToMany(mappedBy = "parent", cascade = [CascadeType.ALL], fetch = FetchType.EAGER)
var children: MutableList<Child> = mutableListOf()
}
Child Entity:
@Entity
class Child(
@Id
@GeneratedValue(generator = "uuid2")
val id: UUID? = null
) : Serializable {
@ManyToOne()
@JoinColumn(name = "myForeignKey", referencedColumnName = "secondaryId")
lateinit var parent: Parent
}
This has the N+1 query problem.. so let's try @NamedGraphEntity!
The problem is, that the @NamedEntityGraph annotation doesn't work.. as the JoinColumn annotation doesn't reference the PrimaryKey of the Parent class.
@Repository
interface ParentRepository : JpaRepository<Parent, UUID> {
// Has the N+1 Query Problem.
@EntityGraph("ParentEntity.children", type = EntityGraph.EntityGraphType.LOAD)
fun findByName(name: String): List<Parent>
}
Question: How do I get the EntityGraph query to work when the JoinColumn is specifying a non-primary column?
What I've tried:
- Tried referencing the primary id, and it fixes the issue .. but migrating existing foreign keys is a heavy lift to get this optimization.