piątek, 1 marca 2013

Quering and queries with parameter(s)

Hello!

I would like to show you, how to retrieve object from db using queries with parameter(s).

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. package pl.selfimproveit.hibernate;
  2. import java.util.List;
  3. import org.hibernate.Query;
  4. import org.hibernate.Session;
  5. import org.hibernate.SessionFactory;
  6. import org.hibernate.cfg.Configuration;
  7. import pl.selfimproveit.model.User;
  8.  
  9. public class Launcher {
  10.     public static void main(String[] args) {
  11.         SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  12.         Session session = sessionFactory.openSession();
  13.         session.beginTransaction();
  14.  
  15.         Query query = session.createQuery("from User u where u.firstName =:name").setParameter("name", "John");
  16.         List<User> users = query.list();
  17.        
  18.         System.out.println(users.size());
  19.         for (User user : users) {
  20.             System.out.println(user);
  21.         }
  22.         session.close();
  23.     }
  24. }
In this example we are searching a user with name "John". This is HQL example where we used only 1 parameter. Please remember that we are using a properties name from User class (I mean firstName, lastName, id -  you cannot use directly column names from your database). We are using now "labeled paramaters", but we can use questions marks (?), but  remember about type of this parameter and their sequence in query.

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1.     Query query = session.createQuery("from User u where u.firstName =?").setParameter(0, "John");
  2.         List<User> users = query.list();
  3.        
  4.         System.out.println(users.size());
  5.         for (User user : users) {
  6.             System.out.println(user);
  7.         }
  8.         session.close();


This above snippet we have the same result using question mark. Rembember that postion of parameters are 0 indexed.

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. Query query = session.createQuery("from User u where u.id =?").setInteger(0, 4);
  2.         List<User> users = query.list();
  3.        
  4.         System.out.println(users.size());
  5.         for (User user : users) {
  6.             System.out.println(user);
  7.         }
In example above, we used an indexed typed parameter (?). You should try to set this parameter to String, BigDecimal etc and examine what will be execute of this code. Sometimes query will be executing fine, when we try to find user with ID= 4 and we set a parameter like a String("4")

Query query = session.createQuery("from User u where u.id =?").setString(0, "4");


This is depend on database vendor, but you shouldn't using query in this way.

You can try to build queries with 2 and more parameters it's very simple.


When simply query with parameter is not enough....


Now, let's imagine that you would like to select all of your users with the first letter of their name is M and their  surname begins with S or B.
Believe me there is a Query but it won't be look nice, there is a rescue .... Criteria !
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. public class Launcher {
  2.  
  3.     public static void main(String[] args) {
  4.  
  5.         SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  6.         Session session = sessionFactory.openSession();
  7.         session.beginTransaction();
  8.        
  9.         Criteria criteria = session.createCriteria(User.class);
  10.         criteria.add(Restrictions.like("firstName", "M%"))
  11.         .add(Restrictions.or(Restrictions.like("lastName", "B%"), Restrictions.like("lastName", "S%")));
  12.            
  13.         List<User> users = criteria.list();
  14.        
  15.         System.out.println(users.size());
  16.         for (User user : users) {
  17.             System.out.println(user);
  18.         }
  19.         session.close();
  20.     }

Criteria iterface is very handy, you can find there many SQL equivalent for example:

- like
-between
- in ( Used in collection, but if you try to find String using "S%" it won't work, it takes full String like "John" and try to find a name in your table contains excatly this String, so any SQL wildcard "doesn't pass the exam here..")
-notNull / isNull and many many others!

I mentioned about method Restriction.in.

Let's look at this example:



Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.like("firstName", "M%")).add(Restrictions.in("lastName", new String[] { "S%", "B%" }));


From the logic point of view this Criteria query should return me the same result like above from snippet, but it's not true. Method Restrictions.in  is searching iterating through every record searching exactly fits String : S%  and after that B% (in meaning String as a String not like a SQL Wildcard).

But if you  modify above Criteria query to the following:



Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.like("firstName", "M%")).add(Restrictions.in("id", new Integer[] {6,7,8,9}));

You will get the output.

Maybe you don't know but MySQL doesn't support charlist wild cards, this mean that query like this

SELECT * FROM User
WHERE lastName LIKE '[KTM]%'

Will cause an error, instead of you should use a regexp something like follow:

select * from User where lastName REGEXP '[KTM].*';










Brak komentarzy:

Prześlij komentarz