Lokesh Pandey
Lokesh Pandey

Reputation: 1789

Failed to create a query for method. Creating a custom query in springboot

I am new to springboot, and I am trying to write a login method which will login user based on emailid and password or phone number and password. In my service I have written something like this

public interface AuthService extends CrudRepository<AuthenticationModel, String> {
    Iterable<AuthenticationModel> findUserByEmailId(String emailId, String password);
    Iterable<AuthenticationModel> findUserByPhoneNumber(Long phoneNumber, String password);
}

I know methods like findUserByEmailId and findUserByPhoneNumber are not written in CrudRepository interface. That's why I am getting this error.

Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.lang.Iterable com.xyz.services.authenticate.AuthService.findUserByPhoneNumber(java.lang.Long,java.lang.String)! No property phoneNumber found for type AuthenticationModel!
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96)

What my concern is how can I implement my custom query in springboot ? I am aware of JPQL and native SQL implementations. But Is this recommended way of doing this ? Say In future I am supposed to implement the search functionality, now search mechanism is itself a huge implementation. Can I implement the JPQL or native SQL implementation in search mechanism ? Or Is there another way which springboot provides which I am not aware of ?

I know there are lot of questions in one post. But I am confused when I tried to drill down to the actual answer on internet.

EDIT: AuthenticationModel.class

public class AuthenticationModel {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @NotNull
    @NotBlank
    @Column(name = "user_uuid", unique = true)
    private UUID userUuid;
    @NotNull
    @NotBlank
    @Email
    @Column(name = "user_email_id", unique = true)
    private String userEmailId;
    @NotNull
    @NotBlank
    @Positive
    @Size(min = 10, max = 10)
    @Column(name = "user_phone_number", unique = true)
    private Long userPhoneNumber;
    @NotNull
    @Column(name = "user_password")
    private String userPassword;
}

Upvotes: 0

Views: 922

Answers (1)

Eklavya
Eklavya

Reputation: 18410

Spring data JPA derived query from the method name. You should use exact field name and parameter also for JPA method naming query. Here use UserEmailId, UserPhoneNumber and UserPassword in method name

List<AuthenticationModel> findByUserEmailIdAndUserPassword(String emailId, String password);
List<AuthenticationModel> findByUserPhoneNumberAndUserPassword(Long phoneNumber, String password);

Here you can read details about JPA method naming query https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods

Upvotes: 3

Related Questions