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();
// 准备数据
@Test
public 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
@Test
public 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();
}
}
}
Hibernate_查询_QueryByCriteria的方式
最新推荐文章于 2023-06-16 21:32:29 发布