LIKE - 休眠命名查询

时间:2014-10-12 21:06:20

标签: java mysql hibernate hql named-query

为什么我使用此命名查询语法错误

@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中有三个地址:

  1. 西班牙
  2. 西班牙马德里
  3. 西班牙马德里圣地亚哥伯纳乌球场
  4. 现在,如果我搜索马德里,西班牙,结果必须包含以上所有内容......

    即:

    西班牙,如%Madrid,西班牙%马德里,西班牙,如%西班牙%

    Santiago Bernabeu体育场,西班牙马德里%Madrid,Spain% Madrid,Spain %Santiago Bernabeu Stadium ,马德里,西班牙%

    依旧......

3 个答案:

答案 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+'%');

在此代码中,将addresslocationAddress替换为包含所需信息的变量。

另请参阅此链接以获取类似信息:How to correctly convert JPQL query using "%"