QBC retrieval and local SQL retrieval

  • QBC query is to query objects by using the Query By Criteria API provided by Hibernate, which encapsulates the dynamic assembly of SQL statements and provides a more object-oriented function interface for query

  • Local SQL query to improve HQL cannot cover all query features

step

  1. Create criteria object
  2. Set various search conditions
  3. Perform retrieval

And and or

@Test
    public   void TestQbcAnd(){
            Criteria criteria=session.createCriteria(Student.class);

            //Use conjunction to representand´╝îIt's also a criterion object
            Conjunction cons=Restrictions.conjunction();
            cons.add(Restrictions.like("name", "s", MatchMode.ANYWHERE));
            Grade grade=new Grade();

            //Criteria object adding criteria object
            criteria.add(cons);
            //System.out.println(criteria.list());

            //Represented by disconnectionor
            Disjunction dis=Restrictions.disjunction();
            dis.add(Restrictions.eq("gender", "male"));
            dis.add(Restrictions.isNull("grade"));

            criteria.add(dis);
            System.out.println(criteria.list());
    } 

Project statistics query

    //Statistical query
    @Test
    public   void TestQbcPrejunction(){
            Criteria criteria=session.createCriteria(Student.class);
            //Query statistics with project
            criteria.setProjection(Projections.count("sid"));

            System.out.println(criteria.uniqueResult());
    } 

Add sorting and set page flipping

//Add sort
        @Test
        public   void TestQbcOrder(){
                Criteria criteria=session.createCriteria(Student.class);
                //Query statistics with project
                criteria.addOrder(Order.desc("name"));


                //Set page flipping
                int pageNo=2;
                int pageSize=5;
                criteria.setFirstResult((pageNo-1)*pageSize);
                criteria.setMaxResults(pageSize);

                System.out.println(criteria.list());
        } 

Local sql query

  • hql and qbc have limitations. At this time, you need to use the native sql statement
@Test
    public   void TestQbcSql(){
        String sql="insert into student (name) Values('ok')";
        SQLQuery sqlQuery=session.createSQLQuery(sql);
        sqlQuery.executeUpdate();
    } 

hql can also perform updates and deletions

@Test
    public   void TestQbcUpdate(){
        String hql="delete from Student s where s.name='ok'";
        Query query=session.createQuery(hql);
        query.executeUpdate();
    } 

Tags: SQL Session Hibernate

Posted on Sun, 03 May 2020 04:34:42 -0400 by skeener