Spring JPA repository JPQL query using a collection of objects

↘锁芯ラ 提交于 2019-12-11 16:53:13

问题


let's say I have the next entity or object:

class Person {    
  BigInteger cardNumber;
  String name;
  int age;
  Address address;
}

Then, I have a List<Person> and I want to find the youngest person based on the cardNumber and name. So, I'd like to write a query similar to this:

@Query("SELECT p FROM Person p WHERE p.cardNumber = :myPerson.cardNumber AND p.name LIKE :myPerson.name ORDER BY p.age ASC")
public List<Person> find(@param("myPerson") List<Person> personList);

My problem is that I'm not so sure how to tackle this, and what approach to use. I've tried passing two collections, List<String> names and List<BigInteger> cardNumbers and the query was something like this:

@Query("SELECT p FROM Person p WHERE p.cardNumber IN (:cardNumbers) AND p.name IN (:names) ORDER BY p.age ASC")
public List<Person> find(@param("cardNumbers") List<BigInteger> cardNumbers, @param("names") List<String> names);

The problem, I need to use the name and the cardNumber as a single value to compare because, they both work as a primary key. I tried to CONCAT(name, cardNumber) and pass to the method a list of strings with the name.concat(cardNumber.toString(()) value but, I found that the JPQL turns the BigInteger in a number like this 1.00 so, to make it work I need to do something like this name.concat(cardNumber.toString(() + ".00"). That way, it works but, I can't hardcode that mapping from BigInteger to String.

Any advice is appreciated. I just want to find a way to pass the collection of the object rather than concatenate those strings in my code and then pass them to the query method.

Thank you.

来源:https://stackoverflow.com/questions/55877193/spring-jpa-repository-jpql-query-using-a-collection-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!