Search code examples
javamysqlhibernatehqlnamed-query

LIKE - hibernate named queries


why I get syntax error using this named query :

@NamedQuery(name = "event_find", query = "from Event where location.address like str('%'+:address+'%') " +
        "or :address like str('%'+location.address+'%'")

and :

Query query = session.getNamedQuery("event_find").setParameter("address", address); // or "%"+address+"%"

how can I solve this problem?

EDIT :

Event :

@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;
    }

    ...

}

Location :

@Entity
@Table(catalog = "control_station")
public final class Location implements Serializable {

    private long id;
    private String address;
    private double latitude;
    private double longitude;

    ...
}

for example suppose we have three addresses in table Location :

  1. Spain
  2. Madrid, Spain
  3. Santiago Bernabeu Stadium, Madrid, Spain

now if I search for Madrid, Spain, the result must contains all of the above...

i.e :

where Spain like %Madrid, Spain% or Madrid, Spain like %Spain%

where Santiago Bernabeu Stadium, Madrid, Spain like %Madrid, Spain% or Madrid, Spain like %Santiago Bernabeu Stadium, Madrid, Spain%

and so on...


Solution

  • thank you guys, the answer is :

    @NamedQuery(name = "event_find", query = "from Event where location.address like concat('%', :address, '%') or :address like concat('%', location.address, '%')")