Home > Software engineering >  Jpa - How to "findBy" two columns while both of them have the same name
Jpa - How to "findBy" two columns while both of them have the same name

Time:08-24

I have a Character-in-Category based Jpa relationship here:

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

    var name: String,   //This one

    @ManyToOne @JoinColumn(name = "category_name", referencedColumnName = "name")
    var category: Category? = null,

    var gender: Gender? = null
): Serializable {
    enum class Gender {
        MALE, FEMALE, OTHER
    }
}
// Category.kt
@Entity
class Category (
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null,

    var name: String? = null,   //Also this one

    @OneToMany(mappedBy = "category") @JsonIgnore
    var characters: MutableSet<Character> = mutableSetOf()
) : Serializable

I have done some "findBy" queries by multiple columns before, but this is the first time that both of them have the same name and i suppose its not working because of that, how can i reach this without changing any of their property names?

// CharacterRepository.kt
@Repository
interface CharacterRepository : JpaRepository<Character, Long> {

    fun findByNameAndCategory_Name(name: String, categoryName: String): Character

}

Edit: What is not working is that findBYNameAndCategory_Name, always returning Result must not be null as a EmptyResultDataAccessException despite the data actually exists in database.

CodePudding user response:

Spring Data follows the path from the root entity in the implements (JpaRepository<Character, Long>): this should work:

Optional<Character> findByNameAndCategoryName(String name, String categoryName)

I don't use Kotlin, so this is Java syntax, but the same should apply for Kotlin: the method name matters.

  • Related