Java Tutorial/Hibernate/LogicalExpression

Материал из Java эксперт
Перейти к: навигация, поиск

Combine AND, OR

File: Main.java



import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Restrictions;
public class Main {
  public static void main(String[] args) throws Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil
        .executeSQLCommand("create table survey (id int,name varchar, purchasedate date);");
    Session session = hibernateUtil.getSession();
    Survey survey = new Survey();
    survey.setName("Survey");
    survey.setPurchaseDate(new Date());
    session.save(survey);
    
    survey = new Survey();
    survey.setName("Survey1");
    survey.setPurchaseDate(new Date());    
    session.save(survey);
    
    session.flush();
    
    Criteria crit = session.createCriteria(Survey.class);
    Criterion price = Restrictions.gt("Id",new Integer(1));
    Criterion name = Restrictions.like("name","S%");
    LogicalExpression orExp = Restrictions.or(price,name);
    crit.add(orExp);
    crit.add(Restrictions.gt("purchaseDate",new Date()));
    
    List results = crit.list();
    
    Iterator iter = results.iterator();
    while (iter.hasNext()) {
      Survey cd = (Survey) iter.next();
      System.out.println("Result Name:"+cd.getName());
    }
    session.close();
    hibernateUtil.checkData("select * from survey");
  }
}