Examples of the use of Criteria queries in Java's Hibernate framework

  • 2020-04-01 04:33:35
  • OfStack

Let's talk about Criteria queries, which are easy for us programmers who are not familiar with SQL statements.
  Without further ado, here are some examples:
  The entity class is as follows:


public class User implements Serializable{ 
 
  private static final long serialVersionUID = 1L; 
  public Long id; 
  private String name; 
  private int age; 
    //Omit the Get/Set method
} 

    We will not write the mapping file, a very simple entity, if you do not understand the children's shoes please refer to my other articles in hibernate classification.
  Next, let's look at how to use Criteria for queries:
 


public static void main(String[] args) { 
 
  Configuration cfg = new Configuration().configure(); 
  SessionFactory sessionFactory = cfg.buildSessionFactory(); 
  Session session = sessionFactory.openSession(); 
   
  Criteria criteria = session.createCriteria(User.class); 
  criteria.add(Restrictions.eq("name","shun")); 
   
  List list = criteria.list(); 
  Iterator iter = list.iterator(); 
  while(iter.hasNext()) { 
    User user = (User)iter.next(); 
    System.out.println(user.getName()+":"+user.getAge()); 
  } 
   
  session.close(); 
} 

    You see the code, it's a very simple string.
  As we all know, we can see the code after constructing session:
 


Criteria criteria = session.createCriteria(User.class); 
criteria.add(Restrictions.eq("name","shun")); 

    These two lines of code are the key points. Let's analyze what they mean.
  In the first sentence we get an object of the Criteria implementation class through session, and then in the second sentence we add a condition through the add method that eq represents equality. Hibernate3 was previously implemented through express.eq, but since Criteria was dropped after 3, we implemented the Restrictions class instead, which is used in the same way as Expression. Let's look at the API and see that Expression inherits from Restrictions.
  Going back to our two sentences above, after we've done all this work, hibernate actually constructed the similarity for us


 select * from user where name='shun' 

    Statements like this. (here we map the User class in the file to the User table, and the name property to the name field.)
 
  Restrictions also has a number of methods to help us construct SQL statements, which you can easily understand by looking at the API.
 
  So let's take a look at the code above, if we close the session, but we want to continue using the criteria, okay? So let's see.
  After the above code, we re - walk, add:
 


List list2 = criteria.list(); 
Iterator iter2 = list.iterator(); 
while(iter.hasNext()) { 
  User user = (User)iter.next(); 
  System.out.println(user.getName()+":"+user.getAge()); 
} 

    In order to distinguish between the previous list and iter, let's use another one here.
  Running it, we get an exception:
 


org.hibernate.SessionException: Session is closed! 

    Declaring this exception means that the session has been closed. In many cases, if we close the session and do saveOrUpdate,save and other operations related to persistence, we will report a similar exception.
  Hibernate3 takes this requirement into account and implements a DetachedCriteria that can exist independently of the Session.
  Let's look at an example :(entity or above)
 


public static void main(String[] args) { 
     
    Configuration cfg = new Configuration().configure(); 
    SessionFactory sessionFactory = cfg.buildSessionFactory(); 
    Session session = sessionFactory.openSession(); 
     
    DetachedCriteria decriteria = DetachedCriteria.forClass(User.class); 
    decriteria.add(Restrictions.eq("name","shun")); 
     
    List list = decriteria.getExecutableCriteria(session).list(); 
    Iterator iter = list.iterator(); 
    while(iter.hasNext()) { 
      User user = (User)iter.next(); 
      System.out.println(user.getName()+":"+user.getAge()); 
    } 
     
    session.close(); 
     
    Session session2 = sessionFactory.openSession(); 
    List list2 = decriteria.getExecutableCriteria(session2).list(); 
    Iterator iter2 = list2.iterator(); 
    while(iter2.hasNext()) { 
      User user = (User)iter2.next(); 
      System.out.println(user.getName()+":"+user.getAge()); 
    } 
  } 

    We see that after the session closes, we can continue with DetachedCriteria in another connection. We need to associate the current DetachedCriteria with a Session through getExecutableCriteria(Session Session).
 
 
  Next, let's look at the use of the Subqueries class with DetachedCriteria:
 


public static void main(String[] args) { 
     
    Configuration cfg = new Configuration().configure(); 
    SessionFactory sessionFactory = cfg.buildSessionFactory(); 
    Session session = sessionFactory.openSession(); 
     
    DetachedCriteria decriteria = DetachedCriteria.forClass(User.class); 
    decriteria.setProjection(Projections.avg("age")); 
     
    Criteria criteria = session.createCriteria(User.class); 
    criteria.add(Subqueries.propertyGt("age",decriteria)); 
    List list = criteria.list(); 
    Iterator iter = list.iterator(); 
    while(iter.hasNext()) { 
      User user = (User)iter.next(); 
      System.out.println(user.getName()+":"+user.getAge()); 
    } 
     
    session.close(); 
     
  } 

    The first line of code you might have questions about is:
 


decriteria.setProjection(Projections.avg("age")); 

    This code refers to the average value of age obtained by decriteria. And then below that you get an object of age that is greater than the average.
  Projections contains a number of wrapper methods for implementing SQL methods, and you can take a look at the API.

Let's take a look at some of its more advanced USES.
  Just look at the code:


criteria.setFirstResult(10); 
criteria.setMaxResults(20); 

    Here we set the record to start at number 10, and then look up 20 records from number 10, so that we can implement the basic paging function.
  Of course, there are many cases where we need to sort, and the criteria support that:


 criteria.addOrder(Order.desc("age")); 

    Here, we simply use the addOrder method, where we get an Order object through order.desc, which requires a property parameter. In fact, when we call addOrder, hibernate will help us generate statements like order by age.
 
  So what do we do when we need to group? So this is going to use the groupProperty method for the movie class that we talked about last time,
 


criteria.setProjection(Projections.groupProperty("age")); 

    Here we are grouping by the age attribute, which is actually grouping by the corresponding field age, and hibernate will automatically translate it into a statement like group by age.
There are many practical methods available in Projections (note that this is only available after hibernate 3).    
 


Related articles: