学下来的感觉就是QBC写起来有点麻烦,但是它可以实现复杂的sql的拼装,还是挺好用的,不过个人推荐使用hql语句实现。至于本地sql的运用,当你需要插入数据时,这个时候hql语句就无能为力了,因为它不支持更新和插入。但是这事Query对象的局限,我们一般用session.save方式更新和插入对象而已下面看代码
@Test
public void testQBC()
{
//1.创建一个Criteria对象
Criteria criteria = session.createCriteria(Employee.class);
//2.添加查询条件,在QBC中查询条件使用Criterion表示
//Criterion可以通过Restrictions的静态方法得到
criteria.add(Restrictions.eq("email", "a13.com"));
criteria.add(Restrictions.lt("salary", 5000d));
//3.执行查询
Employee employee = (Employee) criteria.uniqueResult();
System.out.println(employee);
}
@Test
public void testQBC2()
{
Criteria criteria = session.createCriteria(Employee.class);
//1.AND 使用Conjunction
//Conjunction本省就是Criteria对象,且可以添加Criteria对象
Conjunction conjunction = Restrictions.conjunction();
conjunction.add(Restrictions.like("name", "a", MatchMode.ANYWHERE));
Department department = new Department();
department.setId(1);
conjunction.add(Restrictions.eq("department", department));
System.out.println(conjunction);
//2.OR
Disjunction disjunction = Restrictions.disjunction();
disjunction.add(Restrictions.ge("salary", 6000d));
disjunction.add(Restrictions.isNull("email"));
criteria.add(conjunction);
criteria.add(disjunction);
}
@Test
public void testQBC3()
{
Criteria criteria = session.createCriteria(Employee.class);
//统计查询:使用Projections表示:可以有Projections静态方法得到
criteria.setProjection(Projections.max("salary"));
System.out.println(criteria.uniqueResult());
}
@Test
public void testQBC4()
{
Criteria criteria = session.createCriteria(Employee.class);
//1.添加排序
criteria.addOrder(Order.asc("salary"));
criteria.addOrder(Order.desc("email"));
//2.添加翻页
int pageSize = 5;
int pageNo = 3;
List<Employee> employees = criteria.setFirstResult((pageNo - 1)*pageSize).
setMaxResults(pageSize).list();
System.out.println(employees);
}
@Test
public void testNativeSQL()
{
String sql = "INSERT INTO Departments VALUES(?,?)";
Query query = session.createSQLQuery(sql);
query.setInteger(0, 45).setString(1, "gg").executeUpdate();
}
@Test
public void testHQLDelete()
{
String hql = "DELETE FROM Department d WHERE d.id = :id";
session.createQuery(hql).setInteger("id", 45).executeUpdate();
}