cool hit counter SSH framework journey - hibernate (4)_Intefrankly

SSH framework journey - hibernate (4)


hibernate

1.hibernate query method


    1. Object navigation queries An object is associated with another object, And the two are in a one-to-many relationship, or so By a( a party (in a contract or legal case)) object will be able to find another( in many ways) targets。 for example: By one class you can find all the students in the class, This type of query to find student objects by class objects is called Object navigation queries。
    1. OID Search Also known as object unique identifier query. The get() method of session and the load() method described below are both OID queries based on the unique identifier value in the object's properties.
    1. HQL Query Using Query objects to call related methods to do queries requires writing related hql statements, which is the query language provided by hibernate. hql statements write entity classes and properties, while sql statements write data tables and fields.
    1. QBC Enquiry Use the Criteria object to call related methods to do queries, but without writing statements, the methods are called and operate on entity classes and properties.
    1. SQL Query use SQLQuery object to write ordinary sql statement to do the query, But because of the difference in databases,sql The statements are also different, So this query is generally not used。 But if the underlying database is needed for the SQL When searching for dialects, It's still possible to use this method。hibernate The species is also encapsulated SQL Query object of SQLQuery。

2.Basic Code


The following example is also based on a class and student one-to-many relationship instructions of。

2.1 Entity class code

  • Student entity category
package cc.wenshixin.entity;

public class Student {
     private Integer id;  / / Student number
     private String name;  // Name
     private Integer age;  // Age

     private Banji banji;  // Classes to which one belongs

    public Student() {

    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

     //get, set methods are omitted here and must be written
}
  • Class entity category
package cc.wenshixin.entity;

import java.util.HashSet;
import java.util.Set;

public class Banji {
     private Integer id;  // No.
     private String name;  // Name
    
    private Set<Student> setStudent = new HashSet<Student>(); // Students in the class

    public Banji() {

    }

    public Banji(String name) {
        this.name = name;
    }
     //get, set methods are omitted here and must be written
}
  • tools
package cc.wenshixin.utility;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtility {
    private static Configuration cfg = null;
    private static SessionFactory sessionFactory = null;

    static{
        cfg = new Configuration().configure();
        sessionFactory = cfg.buildSessionFactory();
    }
    
    // acquiresessionFactory Methods of the object
    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }   
}

2.2 Mapping files

  • Student entity class mapping file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cc.wenshixin.entity.Student" table="student">
        <id name="id" type="java.lang.Integer" column="sid">
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String" column="sname">
        </property>
        <property name="age" type="java.lang.Integer" column="age">
        </property>
        <many-to-one name="banji" class="cc.wenshixin.entity.Banji" column="sbid">
        </many-to-one>
    </class>
</hibernate-mapping>
  • Class entity class mapping file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cc.wenshixin.entity.Banji" table="banji">
        <id name="id" type="java.lang.Integer" column="bid">
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String" column="bname">
        </property>
        <set name="setStudent" table="student" cascade="save-update">
            <key column="sbid">
            </key>
            <one-to-many class="cc.wenshixin.entity.Student" />
        </set>
    </class>
</hibernate-mapping>
  • Core Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
      <!--  Database information configuration -->
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql://localhost:3306/ Database name?useUnicode=true&characterEncoding=UTF-8</property>
      <property name="connection.username"> user ID</property>
      <property name="connection.password"> pin number</property>
      
      <!-- hibernate Function Selection -->
      <property name="show_sql">true</property>
      <property name="format_sql">true</property>
      <property name="hbm2ddl.auto">update</property>
      <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
      
      <!--  Loading the mapping file -->
      <mapping resource="cc/wenshixin/entity/Student.hbm.xml"/>
      <mapping resource="cc/wenshixin/entity/Banji.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

2.3 Data initialization

    @Test
    // Initialization data
    public void initData()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            // Insert data
            Banji banji1 = new Banji(" Accounting class");
            Banji banji2 = new Banji(" Accounting Class 2");
            Banji banji3 = new Banji(" Accounting Class 3");
            Banji banji4 = new Banji(" Accounting Class 4");
            
            Student student1 = new Student(" Simon", 20);
            Student student2 = new Student(" small red", 19);
            Student student3 = new Student(" quick witted", 21);
            Student student4 = new Student(" Zhang Xiao", 20);
            Student student5 = new Student(" youngster", 19);
            Student student6 = new Student(" old king", 23);
            Student student7 = new Student(" Wei of the Northern Dynasties", 20);
            
            banji1.getSetStudent().add(student1);
            banji1.getSetStudent().add(student3);
            banji2.getSetStudent().add(student2);
            banji2.getSetStudent().add(student5);
            banji2.getSetStudent().add(student4);
            banji3.getSetStudent().add(student6);
            banji4.getSetStudent().add(student7);
            
            session.save(banji1);
            session.save(banji2);
            session.save(banji3);
            session.save(banji4);
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

2.4 Object navigation queries test (machinery etc)

    @Test
    // Object navigation query method
    public void test()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Banji banji = session.get(Banji.class, 2);
            Set<Student> setStudent = banji.getSetStudent();

            System.out.println(setStudent.size());
            for (Student student : setStudent) {
    System.out.println(student.getId()+":"+student.getName()+":"+student.getAge());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

3. HQL Query


Commonly used hql statements (keywords that are case-sensitive).

    1. Query all. from Entity class name
    1. Conditional queries (set aliases using AS keywords). from Entity class name as nickname where nickname. Property Name=? from Entity class name as nickname where nickname. Property Name=? and nickname. Property Name=? from Entity class name as nickname where nickname. Property Name like ?
    1. Sort query. from Entity class name as nickname order by nickname. Property Name asc/desc
    1. Paging queries: This is done by calling the method to set the start position query.setFirstResult(0); Set the number of records per page query.setMaxResults(3);
  • 5. Projection Search: (located) at Projection Search It's only used in SELECT keyword, which is not used in the previous query, and cannot use the * sign. select Property Name from Entity class name
  • 6. Function Query: (located) atHQL It is also possible to use the sql function,count() Function to calculate the number of,sum() Function Summation,avg() Function to calculate the average value,max() Function to calculate the maximum value,min() The function calculates the most small happen to。

hql statement query steps.

    1. Create the Query object and write the hql statement
    1. Call the methods inside the query object to get the results

3.1 Search all

    @Test
    //HQL Query all data in the table
    public void testQueryAll()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Query<Banji> query = session.createQuery("FROM Banji");
            
            List<Banji> list = query.list();
            
            for(Banji banji:list)
            {
                System.out.println(banji.getId()+":"+banji.getName());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

3.2 Conditional queries

    @Test
    //HQL Query with conditions
    public void testQueryWhere1()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Query<Banji> query = session.createQuery("FROM Banji AS banji WHERE banji.id=?");
            query.setParameter(0, 2);
            
            List<Banji> list = query.list();
            
            for(Banji banji:list)
            {
                System.out.println(banji.getId()+":"+banji.getName());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

    @Test
    // blurred Conditional Search
    public void testQueryWhere2()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Query<Banji> query = session.createQuery("FROM Banji AS banji WHERE banji.name LIKE ?");
            query.setParameter(0, "% computer science%");
            
            List<Banji> list = query.list();
            
            for(Banji banji:list)
            {
                System.out.println(banji.getId()+":"+banji.getName());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

3.3 Sorted queries

    @Test
    // Sort Search
    public void testQueryOrder()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Query<Banji> query = session.createQuery("FROM Banji AS banji ORDER BY banji.id DESC");
            
            List<Banji> list = query.list();
            
            for(Banji banji:list)
            {
                System.out.println(banji.getId()+":"+banji.getName());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

3.4 Paging queries

    @Test
    // Paging queries
    public void testQueryPage()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Query<Student> query = session.createQuery("FROM Student");
            
            query.setFirstResult(2);
            query.setMaxResults(3);
            
            List<Student> list = query.list();
            
            for(Student student : list)
            {
                System.out.println(student.getId()+":"+student.getName()+":"+student.getAge());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

3.5 Projection queries

As lofty as it sounds, it's actually a query for a column in a data table.

@Test
    // Projection Search
    public void testQueryShade()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            // Note that the result returned is aobject types, Instead of a type of entity class
            Query<Object> query = session.createQuery("SELECT name FROM Student");
            
            List<Object> list = query.list();
            
            for(Object object : list)
            {
                System.out.println(object);
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

3.6 Function queries

need types converts

    @Test
    // Function Query
    public void testQueryFunction()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Query<Object> query = session.createQuery("SELECT COUNT(id) FROM Student");
            
            Object object = query.uniqueResult(); // Get the unique value of the query result
            
            // First convert tolong types, reconvert toint types
            Long obj = (Long)object;
            int count = obj.intValue();
            System.out.println(count);
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

4. QBC Enquiry


QBC queries are implemented through the static methods of the Restrictions class, as shown in the table below.

Static methods

instructions

Restrictions.eq()

tantamount to

Restrictions.allEq()

Using Map, use key/value for multiple equals comparison

Restrictions.gt()

more than, > >

Restrictions.ge()

more than, > tantamount to >=

Restrictions.lt()

small in <

Restrictions.le()

small in tantamount to <=

Restrictions.between()

Corresponds to the between statement in the sql statement

Restrictions.like()

Corresponds to the sql like statement

Restrictions.in()

Corresponds to the in statement of sql

Restrictions.and()

and relationships

Restrictions.or()

or relationship

Restrictions.sqlRestriction()

sql limit queries

4.1 Check all

    @Test
    public void testAll()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;      
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            // Search all
            Criteria criteria = session.createCriteria(Student.class);
            List<Student> list = criteria.list();
            
            for (Student student : list) {
                System.out.println(student.getId()+":"+student.getName()+":"+student.getAge());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

4.2 Conditional queries

    @Test
    public void testWhere1()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;      
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            // Conditional Search
            Criteria criteria = session.createCriteria(Student.class);
            criteria.add(Restrictions.eq("id", 4)); // equivalent towhere sid = 4
            criteria.add(Restrictions.eq("age", 19)); 
            List<Student> list = criteria.list();
            
            for (Student student : list) {
                System.out.println(student.getId()+":"+student.getName()+":"+student.getAge());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

    @Test
    public void testWhere2()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;      
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            // Fuzzy queries
            Criteria criteria = session.createCriteria(Student.class);
            criteria.add(Restrictions.like("name", "% small%"));
            List<Student> list = criteria.list();
            
            for (Student student : list) {
                System.out.println(student.getId()+":"+student.getName()+":"+student.getAge());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

4.3 Sorted queries

    @Test
    public void testOrder()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;      
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            // Sort Search
            Criteria criteria = session.createCriteria(Student.class);
            criteria.addOrder(Order.desc("id"));
            List<Student> list = criteria.list();
            
            for (Student student : list) {
                System.out.println(student.getId()+":"+student.getName()+":"+student.getAge());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

4.4 Paging queries

Without further ado, please see the code.

    @Test
    public void testPage()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;      
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            // Paging queries
            Criteria criteria = session.createCriteria(Student.class);
            criteria.setFirstResult(1);
            criteria.setMaxResults(4);
            List<Student> list = criteria.list();
            
            for (Student student : list) {
                System.out.println(student.getId()+":"+student.getName()+":"+student.getAge());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

4.5 Function Query

same HQL the same as,QBC there are also Function Query, pass (a bill or inspection) Projections class Static methods realize。

    @Test
    public void testFunction()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;      
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            // Function Query
            Criteria criteria = session.createCriteria(Student.class);
            criteria.setProjection(Projections.rowCount());
            List<Student> list = criteria.list();
            
            Object obj = criteria.uniqueResult();
            Long lobj = (Long)obj;
            int count = lobj.intValue();
            
            System.out.println(count);
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

4.6 Off-line queries

DetachedCriteria translates to offline conditional query, he does not rely on Session to create, so DetachedCriteria can be used by other layers to encapsulate the condition, before handing over to the DAO layer query, often used in the integration of SSH framework.

    @Test
    public void testOutLine()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;      
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            // Offline Search
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Student.class);
            Criteria criteria = detachedCriteria.getExecutableCriteria(session);
            List<Student> list = criteria.list();
            
            for (Student student : list) {
                System.out.println(student.getId()+":"+student.getName()+":"+student.getAge());
            }
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

5.hibernate retrieval strategy


5.1 Multi-table join query.

When doing queries on tables, sometimes you have to use join queries to do joint queries on tables, here is how to write multi-table queries in mysql.

  • Cross Reference The result of the query returns the Cartesian product of all the data rows in the table being joined, and the number of result entries returned is also the number of data records in one table multiplied by the number of data records in another than table. It is best not to use cross queries in development, as they are extremely inefficient when the amount of data is not very large, and should be avoided when designing data tables. select * from student, banji;
  • internal connection select * from student, banji where student.sid=banji.bid; select * from student inner join banji on student.sid=banji.bid;
  • external connection
    • Left outer connection select * from student left outer join banji on student.sid=banji.bid;
    • Outer right connection select * from student right outer join banji on student.sid=banji.bid;

5.2 HQL join queries

5.2.1 internal connection inquiry

internal connection There are general internal connection inquiry, And urgent. internal connection inquiry, Urgent join queries are more efficient than the usual internal connection The query has an additional fetch The two ways of keyword return different result sets.

    @Test
     //Internal join queries
    public void testQueryInner()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Query<Object> query = session.createQuery("from Banji as b inner join b.setStudent");
            
            List<Object> list = query.list(); // Returns an array of two-dimensional objects,list Each part of the table contains data from two tables
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

    @Test
     // Urgent inner join query
    public void testQueryInnerFecth()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Query<Object> query = session.createQuery("from Banji as b inner join fetch b.setStudent");
            
            List<Object> list = query.list(); // Returns an array of one-dimensional objects, Contains only union tablesstudent The data in the
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

5.2.2 External connections

Outer joins are also divided into general outer join queries and urgent outer join queries, and there are also left outer joins and right outer joins.

    @Test
    // urgency external connection inquiry
    public void testQueryOuterFecth()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Query<Object> query = session.createQuery("from Banji as b left outer join fetch b.setStudent");
            
            List<Object> list = query.list(); // Returns an array of one-dimensional objects, Contains only union tablesstudent The data in the
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }
    
    @Test
    // external connection inquiry
    public void testQueryOuter()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Query<Object> query = session.createQuery("from Banji as b left outer join b.setStudent");
            
            List<Object> list = query.list(); // Returns an array of two-dimensional objects, Contains data from two tables
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

5.3 HQL retrieval (crawling) strategies

The hibernate retrieval strategy is also a way to improve performance by optimizing the statements sent when fetching the associated objects, but the grabbing strategy needs to be used in conjunction with deferred loading to improve performance.

In the previous, the get() method of the session object is used to send statements to query the database, but you can also load() to do the query. The difference between the two is that the get() method sends statements to query the database immediately, while the load() method sends statements to query the database only when it is executed to use the query object statements, and the delayed way of load is the delayed query way.

Delayed queries fall into two categories.

    1. Class level delay: the call to the load method does not immediately send a statement when the entity class object is returned based on the id query.
    1. Associated level delay: Check a class, Then check if all students in a class need a delay, This process is known as Associated level delay。

The delay is whether the sql statement is sent as it is written, or when the data values are used.

Regarding class level delays is the difference between methods, and association level delays need to be configured in the mapping file, to get all students based on class, it needs to be configured in the mapping file of the class entity class. (located) at set Use on labelsfetch attributes and lazy Properties.fetch The default is the select value, if fetch The value of the attribute join or so lazy The value setting inside becomes invalid. set up lazy values: true: for delay (default); false: for no delay; extra for extreme delay.

The following is sample code.

Class level delay

    @Test
     //get query method
    public void testGet()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Banji banji = session.get(Banji.class, 2);
             // This sentence sends the sql statement
            Set<Student> setStudent = banji.getSetStudent();
            
             // The value to be printed in this sentence will only be displayed after a successful transaction commit
            System.out.println(setStudent.size()); 
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

    @Test
     //load query method
    public void testLoad()
    {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
            sessionFactory = HibernateUtility.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            Banji banji = session.load(Banji.class, 2);
             // This sentence does not send a sql statement
            Set<Student> setStudent = banji.getSetStudent();

             //This sentence is what sends the sql statement to display the values that need to be printed after the transaction is committed
            System.out.println(setStudent.size());
            
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }

Associated level delay

Add the following configuration to the configuration file of the class entity class.

<set name="setStudent" table="student" cascade="save-update" lazy="false">
    <key column="sbid">
    </key>
    <one-to-many class="cc.wenshixin.entity.Student" />
</set>

Batch crawl configuration

To further improve the efficiency of the query, hibernate also has a batch-catch configuration, just add the batch-size property to the set file, write a number in it, the larger the number, the less statements sent when querying, the maximum generally write 10.

<set name="setStudent" table="student" cascade="save-update" lazy="false"  batch-size="10">
    <key column="sbid">
    </key>
    <one-to-many class="cc.wenshixin.entity.Student" />
</set>

Recommended>>
1、Software Development Summer Internship
2、Introduction to LinuxBonding and its use in virtual network devices
3、CBS Technology at Cyber Security Expo 2018
4、Top 10 Benefits of Using PHP in Web Development
5、Weak electrical intelligent weak electrical engineering in the necessary cabinet knowledge

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号