Hibernate: search for a user by name, regardless of the order of the name

I have this (simplified) User table bound to POJO User.java thanks to Hibernate:

 +---+------------+-------------+ | | firstName | lastName | +---+------------+-------------+ | 1 | John | Doe | | 2 | John | Poe | +---+------------+-------------+ 

In my user interface, I have a search box to search for users that offers results related to what you type. For example, if I find “ Jo ” in this search field, it offers me 2 results: “ John Doe ” and “ John Poe ”. It works well.

Now I would like this search box to offer me users regardless of the order that I used to enter the name and the name. For example, if I type “ Doe Jo ” he should offer me “ John Doe .”

Here is the query I'm using:

 select u from User u where lower(concat(u.lastName,' ',u.firstName)) like lower(:typedName) or lower(concat(u.firstName,' ',u.lastName)) like lower(:typedName) 

Where typedName is the text entered in the search field. This parameter is included in the request as follows:

 query.setParameter("typedName", typedName+'%'); 
  • If I find " Jo ", " John " or " John D " or more, he finds a good result (s)
  • If I type " D " or " Doe " if I find a good result (s)
  • If I find " Doe J " or more , no result was found .

Why was this last entry unable to find a result? The first part of the condition of my request should be able to handle this, since the second part can process " John D ", no?

Edit

As stated in the comments, I fulfill my request:

 final TypedQuery<User> query = getEntityManager() .createNamedQuery("my_query_name", User.class); query.setParameter("typedName", typedName+'%'); try { return query.getResultList(); } catch (PersistenceException e) { e.printStackTrace(); // for debug purpose } 

Edit 2

Also note that the generated SQL returns me good results for the latter case

+4
source share

All Articles