Hibernate学习笔记----QBC和本地SQL查询

学下来的感觉就是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();
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值