Hibernate, Session object, Query object and HQL

Keywords: Session SQL Database xml

Session object

1. Introduction

  • Session object is the object of database session, which provides the method of interaction with database
  • session object is thread unsafe, so it cannot be used as a global variable

2. Obtaining and closing the session object

How to get / create and close:

        //Get new session object (not commonly used)
        Session session = sessionFactory.openSession(); 
        //Get the current session object (common)
        Session session = sessionFactory.getCurrentSession();
        //Close session (not commonly used)
        session.close();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Where to create and close:
-In order to prevent the problem of uninstantiated objects caused by delayed loading (error no session), session should be created at request time and closed at response time
-The pring framework provides the listener, ContextLoaderListener
In web.xml

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3.Session method

1. Add, delete and modify (o represents an object)

        //delete object
        session.delete(o);
        //Save object
        session.save(o);//Return the id value of the object. Execute immediately, no transaction required
        //Update object; must be within a transaction
        session.update(o);
        //Update with id, save without id
        session.saveOrUpdate(o);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
        //The standard of JPA, for saving, should be in the transaction
        session.persist(o);
        //To update
        session.merge(o);
  • 1
  • 2
  • 3
  • 4

2. check

Check single object

    Session. Get (object. getClass,id); / / execute immediately
    Session. Load (object. getClass,id); / / delay loading (return proxy object, never null; instantiate when using non primary key attribute)
  • 1
  • 2

Query multiple objects

  • Using hql mode
        //Employee representative class
        String hql="select e from Employee e";
        //Generate query object
        Query query = session.createQuery(hql);
        //Query
        List<Employee> list = query.list();//Directly return the encapsulated object
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • Using sql
        //Employee stands for table name
        String sql="select * from Employee e";
        //Generate query object
        Query query = session.createSQLQuery(sql);
        //Query
        List<Object[]> list = query.list(); //Object [], you want to repackage it as an object
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • Use criteria mode (no need for hql and sql statements)
        //Generate query object
        Criteria criteria = session.createCriteria(Employee.class);
        //Query
        List<Employee> list = criteria.list();
  • 1
  • 2
  • 3
  • 4
  • Use NamedQuery method
//Declare the hql statement in the mapping file, and`<class>`after,to`<class>`Same level
<query name="SELECT_ALL_EMPLOYEE">
    select e from Employee
</query>
  • 1
  • 2
  • 3
  • 4
        session.getNamedQuery("SELECT_ALL_EMPLOYEE").list();
  • 1

Query objects and HQL

Query object

Query objects can process query results in advance, as can Criteria objects

        query.list();  //Get query results
        query.uniqueResult(); //Get unique results
        query.setFirstResult(0).setMaxResults(10);//From the first, select ten objects;
        query.setParamter("0","1L");//Set parameters
  • 1
  • 2
  • 3
  • 4

Query combined with HQL

  • Total number of queries
    //HQL=select count(e) from Employee e;
    int count =query.uniqueResult();
  • 1
  • 2
  • 3
  • Set parameters
//Mode 1, use index
    //HQL= select e from Employee e where e.name like ?;
    List<Employee> list = query.setParameter(0,"%Armo%").list();

//Method 2, use name placeholder
    //hql=select e from Employee e where e.name like :name;
    query.setParameter("name","%Armo%").list();
    //hql=select e from Employee e where e.id in (:ids);
    query.setParameter("ids",new Long[]{1L,2L,3L}).list();
    //hql=select e from Employee e where e.dept =:dept;
    query.setParameter("dept",Department object).list();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • Result set processing
//Receive with list < Object >

    //HQL=select (e.name) from Employee e
    List<String> list=query.list();
    //HQL=select new List(e.name,e.id,e.dept) from Employee e;
    List<List<Object>> list=query.list();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
//Receive with list < map < Stirng, Object > >

    //HQL=select new Map(e.name as name,e.id as id,e.dept as dept) from Employee e;
    list<Map<Stirng,Object>> = query.list
  • 1
  • 2
  • 3
  • 4
//Receive with list < instance object >
    //HQL=select new Employee2 (e.id,e.name,e.dept) from Employee1 e;
    List<Employee2> list=query.list();

Employee1 :Class corresponding to mapping file
Employee2 :Another class,You can use full names here,Or alias.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
<! -- set alias in mapping file -- >
    < hibernate mapping package = "domain" auto import = "false" > / / cancel auto alias generation
        < import class = "class full name" rename = "alias" / >
    </hibernate-mapping>

Posted by voyde on Mon, 04 May 2020 21:59:42 -0700