Search code examples
jpaspring-bootspring-dataspring-data-jpa

Error creating bean with name 'customerRepository': Invocation of init method failed; No property updateCustomer found for type Customer


CRUD operations using Spring Boot + JPA + Hibernate + PostgreSQL

Please am new in this topic. Am trying to create a CRUD Api. Everything is ok but i cant get the UPDATE method using the JpaRepository. I dont have error when i build my project.

I try to code a specific createCustomer method into my customerRepository but still not working enter image description here enter image description here

But when i run it with maven i get this error:


Solution

  • Spring data Repository work mostly with method names. It creates query based on the method name. For example in your Repository interface you have a method findByUserId. This will work even if you have not written any query. How ?
    spring-data will formulate the query to fetch the field specified after findBy (UserId in your case). But at compile time, it checks whether you are providing a valid field So that it can prepare a proper query. It does so by checking your entity class (Customer in your case) for this field.

    Note : keep in mind that field in Entity is called userId but method name in Repository is called UserId.

    The reason save, delete methods are working because you are extending JPARepository class(which in-turn extends other classes), which has these methods. So it works out of the box.

    But when you write some method which is not there in any of the super class, then spring-data will try to formulate the query on its own as I specified earlier. So when you write a method like updateCustomer which is not in any of the super classes, then it tries to find in the entity class a field with name updateCustomer and it fails since it cannot find and hence the exception.

    So if you want to declare or do something like this, you can do this by annotating such method with @Query(....) and providing the right query inside it.

    @Query(update customer set ..........)  
    Customer updateCustomer(Customer customer)  
    

    Hope its clear.