Friday, January 3, 2014

Writing NamedQuery with like in where clause

Undoubtedly that you are reading this post because you have run into the trouble with your sql queries especially if like me you are a fervent adept of Sql. But don't panic it is more simpler than you may have thought to do it. Let say for example that your initial sql query looks like the following:
SELECT * FROM school v where v.country like 'CA%';
Now  the named query in your entity bean should be:

        @NamedQuery(name = "School.findByCountry", query = "SELECT v FROM School v WHERE (  v.country LIKE :country)")

Finally we confidently call our named query as follows:
               String pattern= "CA"
    em.createNamedQuery("School.findByCountry")
                 .setParameter("country",   pattern+"%")
                 .getResultList();
Hoping you have gained back your  usual sql honey moon time. Don't forget to drop your comment...

No comments:

Post a Comment