Hibernate (III) openSession and getCurrentSession

1, OID, HQL, SQL, QBC operations

1.1

ibernate has four operation modes, namely OID, HQL, QBC and SQL.  
OID: object identifier. Hibernate is used to mark the unique object. In fact, it is the primary key
Available operations: add, delete, modify and query
For example, we often use
save, update, delete, get, load, saveOrUpdate and other methods
Features: simple operation
Disadvantage: unable to implement complex condition query
Example code:

//oid operation
    @Test
    public void test1(){
        User user=new User();
        user.setPass("11");
        user.setUserName("lx");
        System.out.println(session.save(user));//Preservation
        User user2=session.get(User.class, 3);//query
        user2.setUserName("Hu Han San");
        session.update(user2);//modify
        User user3=new User();
        user3.setId(4);
        session.delete(user3);//delete
    }

1.2

HQL:Hibernate Query Language object oriented query
It is a unique query method of Hibernate
In fact, it is to convert sql into objects
The table is operated before, and the class is operated now
Previously, fields were operated on, now properties are operated on
A piece of data previously operated on. Now the object is operated on
For example: from User
This User is the class name, not the
The object to operate on HQL is Query
HQL can realize: modify, delete, query, complex conditions, aggregate function call, etc
Example code:

//HQL operation
    @Test
    public void test2(){
        //1. Query entity
        String hql1="from User";
        //String hql1="select new User(id,username,pass) from User"; / / query the entity and write it completely
        Query<User> query=session.createQuery(hql1,User.class);//Get object for HQL operation
        List<User> list=query.getResultList();//Get results of multiple queries
        User user=query.uniqueResult();//Get a single result. The result must be one, otherwise an exception will be reported
        //2. Query by criteria
        String hql2="from User where id=?";//Index placeholder
        //String hql2="from User where id=:id"; / / name the placeholder
        Query<User> query2=session.createQuery(hql2);
        query2.setParameter(0, 1);//Bit index placeholder, assignment, starting at 0
        //query2.setParameter("id", 1); / / name placeholder and assign value
        User user2=query2.getSingleResult();//Get unique object
        //3. Using functions
        String hql3="select COUNT(id) from User";
        Query<Long> query3=session.createQuery(hql3);
        long count=query3.getSingleResult();
        //4. Use paging
        String hql4="from User";
        Query<User> query4=session.createQuery(hql4,User.class);
        query4.setFirstResult(0);//Set starting row index: (current number of pages - 1) * number of displayed pages
        query4.setMaxResults(10);//Quantity per page
        List<User> list4=query4.getResultList();
        //5, modify
        String hql5="update User set pass=:pass where id=:id";
        Query query5=session.createQuery(hql5);
        query5.setParameter("pass","123456");
        query5.setParameter("id",3);
        query5.executeUpdate();
        //6, delete
        String hql6="delete from User where id=?";
        Query query6=session.createQuery(hql6);
        query6.setParameter(0, 3);
        query6.executeUpdate(); 
    }

1.3

QBC:Query By Criteria is out of date
Is a simplified query operation of HQL
Purpose: you can query complex conditions without writing keywords of various queries
But hibernate 5.2.1x is out of date
Example code:

//QBC query operation
    @Test
    public void test3(){
        Session session=HibUtils.getCurrentSession();
        Transaction tran=session.beginTransaction();
        //Create object to operate on QBC
        Criteria criteria=session.createCriteria(User.class);
        //Add various conditions
        criteria.add(Restrictions.in("id", new Integer[]{1,2,3}));//in
        criteria.add(Restrictions.and(Restrictions.ilike("pass", "%1%")));//like fuzzy query
        //Get all the results of the query
        List<User> list=criteria.list();

        tran.commit();
    }

1.4

SQL:Hibernate supports native SQL operations
It can be added, deleted, modified and checked
Write SQL statement by yourself
Example code:

/ SQL Query operation
    @Test
    public void test4() {
        Session session = HibUtils.getCurrentSession();
        Transaction tran = session.beginTransaction();
        String sql="select * from tb_user";//Write SQL statement by yourself
        //The former way of writing is now out of date
        //NativeQuery<User> query=session.createSQLQuery(sql);
        //The present way of writing
        NativeQuery<User> query=session.createNativeQuery(sql);
        List<User> list=query.getResultList();
        tran.commit();
    }

1.5 complete test code

public class QueryTest {

    private Session session;
    private Transaction tran;

    @Before
    public void pre() {
        session = HibUtils.getCurrentSession();
        tran = session.beginTransaction();
    }

    // oid operation
    @Test
    public void test1() {
        User user = new User();
        user.setPass("11");
        user.setUserName("lx");
        System.out.println(session.save(user));// Preservation
        User user2 = session.get(User.class, 3);// query
        user2.setUserName("Hu Han San");
        session.update(user2);// modify
        User user3 = new User();
        user3.setId(4);
        session.delete(user3);// delete

    }

    // HQL operation
    @Test
    public void test2() {
        // 1. Query entity
        String hql1 = "from User";
        // String hql1="select new User(id,username,pass) from User"; / / query the entity and write it completely
        Query<User> query = session.createQuery(hql1, User.class);// Get object for HQL operation
        List<User> list = query.getResultList();// Get results of multiple queries
        User user = query.uniqueResult();// Get a single result. The result must be one, otherwise an exception will be reported
        // 2. Query by criteria
        String hql2 = "from User where id=?";// Index placeholder
        // String hql2="from User where id=:id"; / / name the placeholder
        Query<User> query2 = session.createQuery(hql2);
        query2.setParameter(0, 1);// Bit index placeholder, assignment, starting at 0
        // query2.setParameter("id", 1); / / name placeholder and assign value
        User user2 = query2.getSingleResult();// Get unique object
        // 3. Using functions
        String hql3 = "select COUNT(id) from User";
        Query<Long> query3 = session.createQuery(hql3);
        long count = query3.getSingleResult();
        // 4. Use paging
        String hql4 = "from User";
        Query<User> query4 = session.createQuery(hql4, User.class);
        query4.setFirstResult(0);// Set starting row index: (current number of pages - 1) * number of displayed pages
        query4.setMaxResults(10);// Quantity per page
        List<User> list4 = query4.getResultList();
        // 5, modify
        String hql5 = "update User set pass=:pass where id=:id";
        Query query5 = session.createQuery(hql5);
        query5.setParameter("pass", "123456");
        query5.setParameter("id", 3);
        query5.executeUpdate();
        // 6, delete
        String hql6 = "delete from User where id=?";
        Query query6 = session.createQuery(hql6);
        query6.setParameter(0, 3);
        query6.executeUpdate();
    }

    // QBC query operation
    @Test
    public void test3() {
        Session session = HibUtils.getCurrentSession();
        Transaction tran = session.beginTransaction();
        // Create object to operate on QBC
        Criteria criteria = session.createCriteria(User.class);
        // Add various conditions
        criteria.add(Restrictions.in("id", new Integer[] { 1, 2, 3 }));// in
        criteria.add(Restrictions.and(Restrictions.ilike("pass", "%1%")));// like fuzzy query
        // Get all the results of the query
        List<User> list = criteria.list();

        tran.commit();
    }

    // SQL query operation
    @Test
    public void test4() {
        Session session = HibUtils.getCurrentSession();
        Transaction tran = session.beginTransaction();
        String sql="select * from tb_user";//Write SQL statement by yourself
        //The former way of writing is now out of date
        //NativeQuery<User> query=session.createSQLQuery(sql);
        //The present way of writing
        NativeQuery<User> query=session.createNativeQuery(sql);
        List<User> list=query.getResultList();
        tran.commit();
    }

    @After
    public void end() {
        tran.commit();
    }
}
//HibUtils' own encapsulated tool class is used to load database configuration information and create Session object
public class HibUtils {

    private static SessionFactory factory;
    static {
        factory = new Configuration().configure().buildSessionFactory();
    }

    //Safe and efficient
    public static Session getCurrentSession() {
        return factory.getCurrentSession();
    }
    }

Tags: Session SQL Hibernate Database

Posted on Sun, 29 Mar 2020 11:52:57 -0700 by buddhika2010