1. 程式人生 > >hibernate中的Query查詢和criteria查詢的區別

hibernate中的Query查詢和criteria查詢的區別

Query查詢:

	<span style="font-size:18px;">session = HibernateUitl.getSession();
			String hql = "from User as user where user.name =:n";
			//得到一個Query物件
			Query query = session.createQuery(hql);
			//為hql中的屬性賦值
			query.setString("n", name);
			//
			List<User>list = query.list();
			//輸出查詢結果
			for(User user : list){
				System.out.println(user.getname());
			}</span>

criteria查詢:

<span style="font-size:18px;">session = HibernateUitl.getSession();
			//查詢語句
			Criteria c = session.createCriteria(User.class);
			//新增約束條件
			c.add(Restrictions.eq("name", name));
			//得到查詢結果user
			User user = (User)c.uniqueResult();</span>