什么是QBc:
QBC(Query By Criteria)按条件查询,通过Criteria构造查询条件,即通过调用Criteria的api实现各种查询。
通过Criteria对象拼装 查询条件,调用Criteria的add方法拼接查询条件,最终hibernate通过criteria对象自动生成sql语句。
package com.zking.crm.dao.impl;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import com.zking.crm.dao.CstCustomerDao;
import com.zking.crm.domain.CstCustomer;
import com.zking.crm.uilt.hibernateUtli;
public class CstCustomerDaoImpl implements CstCustomerDao {
// @Override
// public void insert(CstCustomer cstCustomer) {
// // TODO Auto-generated method stub
// Session session = hibernateUtli.openSession();// 创建一个session
// Transaction beginTransaction = session.beginTransaction();
// try {
// session.save(cstCustomer);
// beginTransaction.commit();// 提交事务
// } catch (Exception e) {
// // TODO: handle exception
// e.printStackTrace();
// beginTransaction.rollback();// 会滚事务
//
// } finally {
// session.close();
// }
// }
// 优化以后的增加基本客户信息
@Override
public void insert(CstCustomer cstCustomer) {
Session session = hibernateUtli.getCurrentSession();// 获取与当前线程绑定的session
session.save(cstCustomer);
}
@Override
public Long findCustomerCount(DetachedCriteria detachedCriteria) {
// TODO Auto-generated method stub
Session session = hibernateUtli.openSession();
Criteria criteria = detachedCriteria.getExecutableCriteria(session);// 转成可执行的对象
criteria.setProjection(Projections.rowCount());// select Count(*) from 表名
Long totla = (Long) criteria.uniqueResult();// 反回
return totla;
}
@Override
public List<CstCustomer> findCustomerList(DetachedCriteria detachedCriteria, int firstResult, int maxResults) {
// TODO Auto-generated method stub
Session session = hibernateUtli.openSession();
Criteria criteria = detachedCriteria.getExecutableCriteria(session);// 转成可执行的对象
criteria.setFirstResult(firstResult);// 设置其实记录
criteria.setMaxResults(maxResults);// 设置每页显示多少条
return criteria.list();
}
}