Sai
Sai

Reputation: 73

JPA OR condition with single value

I have a table company: companyId number, companyName varchar, address nvarchar. I want to achieve a goal that user can query to fetch company either using a id or company name, image there is a search box, user only has to input a single value, then it will fetch company information.

I wrote an repository

@Query(value = "select c from CompanyBasicInfo c where c.companyID = ?1 or c.companyName = ?1 ")
List<CompanyBasicInfo> findByCompanyIDOrCompanyName(@PathVariable String input);

But when I query, I got an error: Parameter value [10083769] did not match expected type [java.lang.Long (n/a)]

How can I solve this problem? Most of the materials available are something like findByFirstnameOrLastname which uses two values. Thanks a lot!

Upvotes: 3

Views: 6315

Answers (2)

Johannes
Johannes

Reputation: 1

This is not a problem of parameters amount but of its type

You can try to treat companyId as String in query using cast function like here. How do I write hql query with cast?

Your code will look like

@Query(value = "select c from CompanyBasicInfo c where cast(c.companyID as String) = ?1 or c.companyName = ?1 ")
List<CompanyBasicInfo> findByCompanyIDOrCompanyName(@PathVariable String input);

Upvotes: -1

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31215

If none of the companies have a name which consists only of digits, you can create 2 methods (by companyId / by company name) and check wether your input is a number.

If you do not want to do this, you can use the "2 params" version :

List<CompanyBasicInfo> findByCompanyIDOrCompanyName(Long companyId, String companyName);

Then parse your input :

List<CompanyBasicInfo> find(String input) {
  Long companyId = null;
  try {
    companyId = Long.valueOf(input);
  } catch(Exception ignored){}

  return repository.findByCompanyIDOrCompanyName(companyId, input);
}

Upvotes: 2

Related Questions