'Spring returns too many results when query nested object

I have an entity (main class) with a nested object with an OneToMany relation. Everything works fine when I only query the main class. But when I query the nested class too, then the returned list contains much more data as expected. It seems like Spring would somehow join those 2 tables in an unexpected way. For example the json result does not contain 1 main object with a nested objects of 12 list entries. But it contains 12 times the same main object, each having a nested object of 12 list entries. I only need the main object once.

My project is up to date and uses most recent versions.

Main Class:

@Entity
class MainClass(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null,
    var mainField: Long? = null,

    @OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY)
    @JoinColumn(name = "main_id")
    var nested: MutableList<NestedClass?>? = null
)

Nested Class:

@Entity
class NestedClass(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null,

    var main_id: Long? = null,
    var field: Int? = null,
)

Repo:

interface MainClassRepo : CrudRepository<MainClass, Long?> {
    // works fine!
    fun findAllByMainField(
        mainField: Int?,
    ): List<MainClass>

    // returns too many results
    fun findAllByMainFieldAndNestedFieldLessThan(
        mainField: Int?,
        field: Int?,
    ): List<MainClass>
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source