detached entity passed to persist - on findByMethod

I understand the error message and i know how to solve it, but i want to know why it occurs in this specific place especially on a find method. I created a mini example for this.

I have three entitys:

@Entity
data class Animal(
    var name: String,
    @ManyToOne(cascade = [CascadeType.ALL]) val zoo: Zoo) {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Int = -1
}

@Entity
data class Zoo(
    var city: String,
    @OneToMany(cascade = [CascadeType.ALL]) val employee: MutableList<Person>) {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Int = -1
}

@Entity
data class Person(var age: Int) {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Int = -1
}

Service:

   @Transactional
    fun save(name:String, city: String){
        repo.findByZooCity(city).ifPresent {
            it.zoo.employee.add(Person(22))
        }
        repo.findByZooCity("OTHER STRING!!!!").ifPresent { println("FOUND!") }
        repo.save(Animal(name, Zoo(city, mutableListOf(Person(33)))))
    }

Repo:

interface AnimalRep: JpaRepository<Animal, Int>{

    fun findByZooCity(name: String): Optional<Animal>
}

Call:

  animalService.save("Zoo1", "Animal1")
  animalService.save("Zoo1", "Animal1")

Exception: On the second call i get a "detached entity passed to persist: com.example.Person" on repo.findByZooCity("OTHER STRING!!!!"). I know this happens because i add a "detached" person before. But WHY it occurs on a findBy? (Even its not in results?)

Is there some dirty check?

Thank you for your time and help.



Comments

Popular posts from this blog

Spring Elasticsearch Operations

Object oriented programming concepts (OOPs)

Spring Boot and Vaadin : Filtering rows in Vaadin Grid