hibernate的查询

1、条件查询

	public List<Weibo> selectOne(int k){
		Session session = HibernateUtil.currentSession();
		try {
			Criteria c=session.createCriteria(Weibo.class);
			c.add(Restrictions.eq("weiboId","M_Boj1Wc4xC"));//eq是等于,gt是大于,lt是小于,or是或
			List<Weibo> list = (List<Weibo>)c.list();
			return list;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.err.println("select failed!!!!!!");
		}finally{
			HibernateUtil.closeSession();
			HibernateUtil.sessionFactory.close();
		}
		return null;
	}


2、limit查询

		Session session = HibernateUtil.currentSession();
		try {
			//from后面是对象,不是表名
			String hql="from Weibo as weibo";//使用命名参数,推荐使用,易读。
			Query query = session.createQuery(hql);
			query.setFirstResult(k);  
            query.setMaxResults(1);
			List<Weibo> list = (List<Weibo>)query.list();
			return list;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.err.println("select failed!!!!!!");
		}finally{
			HibernateUtil.closeSession();
			HibernateUtil.sessionFactory.close();
		}
		return null;
	}


3、sql查询

	public List<String> selectOne1(int k){
		Session session = HibernateUtil.currentSession();
		try {
			String sql = "select image from t_weiboo limit 5,1;";
			Query query = session.createSQLQuery(sql);
			List<String> list = query.list();
			return list;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.err.println("select failed!!!!!!");
		}finally{
			HibernateUtil.closeSession();
			HibernateUtil.sessionFactory.close();
		}
		return null;
	}

4、id查询

	public void update1() {
		
		Session session = HibernateUtil.currentSession();
		Transaction tx = session.beginTransaction();
		Weibo wb = (Weibo) session.get(Weibo.class, 3);
		wb.setImagePath("");
		session.update(wb);
		tx.commit();

	}

5、唯一结果查询

<span style="white-space:pre">	</span>public Weibo selectOne1(int k){
		Session session = HibernateUtil.currentSession();
		try {
			//from后面是对象,不是表名
			String hql="from Weibo as weibo";//使用命名参数,推荐使用,易读。
			Query query = session.createQuery(hql);
			query.setFirstResult(k);
            query.setMaxResults(1);
			Weibo weibo = (Weibo)query.uniqueResult();
			return weibo;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.err.println("select failed!!!!!!");
		}finally{
			HibernateUtil.closeSession();
			HibernateUtil.sessionFactory.close();
		}
		return null;
	}



posted on 2015-06-04 20:46  长456风  阅读(130)  评论(0编辑  收藏  举报

导航