Adamo
Adamo

Reputation: 596

JpaRepository Interface - No property owner found

I got a strange error even though I think everything looks OK.

Pet class:

@Entity
public class Pet {

    @Id
    @GeneratedValue
    private long id;
    ....
    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "owner_id")
    private PetOwner petOwner;
}

PetOwner

@Entity(name = "pet_owner")
public class PetOwner extends User{
     ...
    @OneToMany(cascade = CascadeType.ALL,mappedBy = "petOwner")
    private List<Pet> pets;
}

Pet Repository

@Repository
public interface PetRepository extends JpaRepository<Pet, Long> {
    List<Pet> findByOwner(PetOwner owner);
}

As you can see i want to get a list of animals giving the owner. During application running get the error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'petRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property owner found for type Pet!

Why get this error?

Upvotes: 0

Views: 149

Answers (1)

Ali Dehghani
Ali Dehghani

Reputation: 48133

Since you named your field as petOwner, you should use findByPetOwner method name instead of findByOwner:

@Repository
public interface PetRepository extends JpaRepository<Pet, Long> {
    List<Pet> findByPetOwner(PetOwner owner);
}

Spring Data JPA attempts to construct a store-specific query from the query method name. The general approach is to remove a given set of well-known prefixes (e.g. find...By or get...By) from the method name and parse the rest of the method using Property Expressions (e.g. petOnwer, in your case) and set of Clauses like Top, Distinct, OrderBy. Those Property expressions can refer only to a direct property of the managed entity. In your case since your property name is petOwner, you can not use owner or anything besides the petOwner. You can read more about this concept here.

Upvotes: 2

Related Questions