hibernate中的HQL和QBC查询

 

创建session及事务

    //1.读取src下hibernate.cfg.xml配置文件
        Configuration cft = new Configuration();
        Configuration configure = cft.configure();
        //2.建立sessionFactory工厂
        SessionFactory sessionFactory = configure.buildSessionFactory();
        //3.打开session回话
        Session session = sessionFactory.openSession();
        
        //4.建立事务
        Transaction transaction = session.beginTransaction();
  1. HQL

          查询所有

  1.         // Query方法查询所有 from + 表对应的实体类   
             Query query = session.createQuery("from Teacher");//通过控制Teacher实体操作数据表
             List teachers = query.list();
    

    条件查询

            Query query = session.createQuery("from Teacher t where t.tname=?");
            query.setParameter(0, "老司机1");//问号的序号从0开始
            List list = query.list();

    顺序查询

            //desc降序 asc升序 
            Query query = session.createQuery("from Teacher order by tid desc");
            List list = query.list();

    模糊查询

     Query query = session.createQuery("from Teacher t where t.tname like ?");//?代表占位符
            query.setParameter(0, "%1%");
            List list = query.list();

    分页查询

     Query query = session.createQuery("from Teacher");
            //设置开始位置既最小id
            query.setFirstResult(0);
            //设置每页记录数
            query.setMaxResults(2);
            List list = query.list();

     

  2. QBC 

  查询所有

        Criteria criteria = session.createCriteria(Teacher.class);//查询Teacher对应的数据表
        List list = criteria.list();

条件查询

        Criteria criteria = session.createCriteria(Teacher.class);
        criteria.add(Restrictions.eq("tid", 3));//tid=3
        criteria.add(Restrictions.eq("tage", "25"));//tage=25
        List list = criteria.list();

模糊查询

        Criteria criteria = session.createCriteria(Teacher.class);
        criteria.add(Restrictions.like("tname", "%1%"));//tname like ("%1%")
        List list = criteria.list();

顺序查询

        Criteria criteria = session.createCriteria(Teacher.class);
        criteria.addOrder(Order.desc("tid"));
        List list = criteria.list();

分页查询 

        Criteria criteria = session.createCriteria(Teacher.class);
        criteria.setFirstResult(0);
        criteria.setMaxResults(2);
        List list = criteria.list();

 

你可能感兴趣的:(hibernate)