susu
susu

Reputation: 109

Hibernate Named Query (HQL) search with keyword

I would like to create a query where able to search person name based on wild-card search of person fullname or person username.

Upvotes: 0

Views: 1271

Answers (1)

Ish
Ish

Reputation: 4154

I'm actually quite confused. You say you entity class is named PersonEntity.java and yet your HQL query selects from Operson.

In HQL, you query against a Java object not an actual table. Anyway, I will assume that your Entity is named Operson. Here's the correct code:

public List<Operson> searchPerson(String keyword) {
    try {
        String HQL = "SELECT o FROM Operson o WHERE o.opusername like :username OR o.opname like :name";
        return em.createQuery(HQL)
          .setParameter("username", "%" + keyword.toUpperCase() + "%")
          .setParameter("name", "%" + keyword.toUpperCase() + "%")
          .getResultList();

    } catch(Exception e) {
        e.printStackTrace();
    }
}

Note:

  1. When using parameters, you don't include the wildcard characters in your HQL query. You use the wildcard characters when you are setting the actual parameters via setParameter().
  2. Your method should return List

Upvotes: 1

Related Questions