为什么我使用此命名查询语法错误:
@NamedQuery(name = "event_find", query = "from Event where location.address like str('%'+:address+'%') " +
"or :address like str('%'+location.address+'%'")
和:
Query query = session.getNamedQuery("event_find").setParameter("address", address); // or "%"+address+"%"
我该如何解决这个问题?
编辑:
活动:
@NamedQueries({
@NamedQuery(name = "event_find", query = "from Event where location.address like :address " +
"or :address like location.address")
})
@Entity
@Table(catalog = "control_station")
public final class Event implements Serializable {
private long id;
private Location location;
...
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
...
}
地点:
@Entity
@Table(catalog = "control_station")
public final class Location implements Serializable {
private long id;
private String address;
private double latitude;
private double longitude;
...
}
例如,假设我们在表Location
中有三个地址:
现在,如果我搜索马德里,西班牙,结果必须包含以上所有内容......
即:
西班牙,如%Madrid,西班牙%或马德里,西班牙,如%西班牙%
Santiago Bernabeu体育场,西班牙马德里如%Madrid,Spain%或 Madrid,Spain 如%Santiago Bernabeu Stadium ,马德里,西班牙%
依旧......
答案 0 :(得分:2)
@NamedQuery(name = "event_find", query = "from Event where location.address like concat('%', :address, '%') or :address like concat('%', location.address, '%')")
答案 1 :(得分:1)
我不是Hibernate的专家,但据我所知,你可能有两个问题:
%
放在setParameter()
调用中,而不是直接放在命名查询中。这也意味着你最终会得到两个参数。str()
,因为location.address
可能已经是一个字符串。此外,您的str()
电话结束时似乎缺少一个括号。所以,我会尝试这样的事情:
@NamedQuery(name = "event_findLike", query = "from Event where location.address like :addressLike " +
"or :address like '%'+location.address+'%'")
和
Query query = session.getNamedQuery("event_findLike").setParameter("addressLike", "%"+address+"%").setParameter("address", address);
答案 2 :(得分:1)
命名查询应该是这样的:
@NamedQuery(name = "event_findLike", query = "from Event where location.address like str(:address) " +
"or :address like :locationAddress
您不应在此命名查询中使用%
。
您可以在设置如下参数时使用%
符号:
Query query = session.getNamedQuery("event_findLike")
.setParameter("address", '%'+address+'%')
.setParameter("locationAddress", '%'+locationAddress+'%');
在此代码中,将address
和locationAddress
替换为包含所需信息的变量。
另请参阅此链接以获取类似信息:How to correctly convert JPQL query using "%"