Java 在JPQL中为过滤器添加两个字符串变量?
假设我有一个具有两个变量的实体:名称和姓氏。我想创建一个JPQL方法,它将返回一个对象列表,这些对象的名称+“”+姓氏将与搜索匹配。我尝试过创建以下JPQL方法,但它不起作用。我本可以在我的实体类中创建一个额外的变量,该变量将汇总名称和姓氏;但这是不好的做法。非常感谢Java 在JPQL中为过滤器添加两个字符串变量?,java,jpa,jpql,Java,Jpa,Jpql,假设我有一个具有两个变量的实体:名称和姓氏。我想创建一个JPQL方法,它将返回一个对象列表,这些对象的名称+“”+姓氏将与搜索匹配。我尝试过创建以下JPQL方法,但它不起作用。我本可以在我的实体类中创建一个额外的变量,该变量将汇总名称和姓氏;但这是不好的做法。非常感谢 public List<User> findUserByFullName(String fullName) { return entityManager.createQuery("select c f
public List<User> findUserByFullName(String fullName) {
return entityManager.createQuery("select c from DefaultUser c where c.name + ' ' + c.surname like :custName").setParameter("custName", fullName)
.getResultList();
}
公共列表findUserByFullName(字符串fullName){
返回entityManager.createQuery(“从DefaultUser c中选择c,其中c.name+“”+c.NastName like:custName”).setParameter(“custName”,fullName)
.getResultList();
}
您是否可以在Java中拆分名称,然后查询拆分名称
这将允许数据库也正确地使用其索引
String[] names = fullName.split(" ");
return entityManager.createQuery("select c from DefaultUser c where c.name = :name and c.surname like :surName").setParameter("name", names[0]).setParameter("surName", names[names.length-1]).getResultList();
在JPQL查询中使用
CONCAT
函数形成全名,如下所示:
select c from DefaultUser c where concat(c.name, ' ', c.surname) like :custName
有关详细信息,请参见中的第4.6.17.2.1节字符串函数。非常感谢Tim B。完全忘记了.split()方法。不过,我不知道可以为JPQL结果指定两个参数,所以非常感谢,今天我学到了一些新东西。