Hibernate_查询_QueryByCriteria的方式

来源:互联网 发布:linux sp2 1503 编辑:程序博客网 时间:2024/05/16 19:22
package cn.itcast.k_query_qbc;import java.util.Arrays;import java.util.List;import org.hibernate.Criteria;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.criterion.Order;import org.hibernate.criterion.Restrictions;import org.junit.Test;/** * 应用程序操作类 *  * @author 风清杨 * @version V3.0 *  */@SuppressWarnings("unchecked")public class App {private static SessionFactory sessionFactory = new Configuration()//.configure()//.addClass(Department.class)//.addClass(Employee.class)//.buildSessionFactory();// 准备数据@Testpublic void testSave() throws Exception {Session session = sessionFactory.openSession();Transaction tx = null;try {tx = session.beginTransaction();// ------------------------------------// 保存一些部门for (int x = 1; x <= 10; x++) {Department department = new Department();department.setName("开发部_" + x);// 保存session.save(department);}// 保存一些员工for (int x = 1; x <= 20; x++) {Employee employee = new Employee();employee.setName("李xx_" + x);// 保存session.save(employee);}// ------------------------------------tx.commit();} catch (RuntimeException e) {tx.rollback();throw e;} finally {session.close();}}// 使用QBC查询:Query By Criteria@Testpublic void testQBC() throws Exception {Session session = sessionFactory.openSession();Transaction tx = null;try {tx = session.beginTransaction();// ------------------------------------// 创建Criteria对象Criteria criteria = session.createCriteria(Employee.class);// >> 增加过滤条件criteria.add(Restrictions.ge("id", 1));criteria.add(Restrictions.le("id", 5));// >> 增加排序条件criteria.addOrder(Order.desc("name"));criteria.addOrder(Order.desc("id"));// ----- 执行查询// criteria.setFirstResult(0);// criteria.setMaxResults(100);// criteria.uniqueResult();// criteria.list();List<Object> list = criteria.list();// ----- 显示结果for (Object obj : list) {if (obj.getClass().isArray()) {// 是数组System.out.println(Arrays.toString((Object[]) obj));} else {System.out.println(obj);}}// ------------------------------------tx.commit();} catch (RuntimeException e) {tx.rollback();throw e;} finally {session.close();}}}

0 0
原创粉丝点击