Hibernate in the Java Framework

Posted by m3rajk on Mon, 08 Jun 2020 20:17:25 +0200

Start Hibernate from scratch: (Four actual combat codes, step by step, notes and learning content in the code notes, for use by students with a certain foundation)

First: Basic (Build)

Basic Hibernate development steps:

1. Import the jar package (find the required jar package in the file of hibernate-release-5.0.7.Final\lib)

2. Write mapping file for entity class + entity class

User.java

/**
 * Project Name:hibernate_demo
 * File Name:User.java
 * Package Name:cn.itcast.entity
 *
*/

package cn.itcast.entity;

/**
 * @author zhouP
 * @version
 * @see
 */
public class User {

    // hibernate Requires an entity class to have an attribute unique
    private int uid;

    private String username;

    private String password;

    private String address;

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getUid() {
        return uid;
    }

}

User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!-- 1. Configuration class and table corresponding class attribute: entity class full path (class path) table attribute: database table name-->
    <class name="cn.itcast.entity.User" table="t_user">
        <!-- 2. Configuring the corresponding hibernate between entity class id and table id requires entity class to have an attribute unique value hibernate requires table fields as unique values-->
        <!--id tag name attribute: ID attribute name column attribute inside entity class: generated table field name-->
        <id name="uid" column="uid">
            <!--Configure growth policy for database table id native:Primary key autogrowth-->
            <generator class="native"></generator>
        </id>

        <!--Configure the name attribute for other attributes and table fields: entity class attribute name column attribute: Generate table field name-->
        <property name="username" column="username"></property>
        <property name="password" column="password"></property>
        <property name="address" column="address"></property>
        
    </class>

</hibernate-mapping>

3.Hibernate Core Profile

<?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>
<!-- Part 1: Configuring database information (required) -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<!-- Part Two: Configuration hibernate Information (optional) -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- Two key configurations ddl,dialect(Paging with) -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Part 3: Put the mapping file in the core configuration file (required) (file path) -->
<mapping resource="cn/itcast/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

4. Write Hibernate tool classes

package cn.itcast.utils;

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

public class HibernateUtils {

    // Establish sessionFactory The process, especially a waste of resources, suggests that a project be generally created sessionFactory object
    // static Configuration cfg = null;

    static SessionFactory sessionFactory = null;
    // Static Code Block Implementation
    static {
        // cfg = new Configuration();
        // cfg.configure();
        // sessionFactory = cfg.buildSessionFactory();
        sessionFactory = new Configuration().configure().buildSessionFactory();

    }

    // Provide Method Return sessionFactory
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

5. Test code

package cn.itcast.hibernatetest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.entity.User;
import cn.itcast.utils.HibernateUtils;

public class HibernateDemo {

    @Test
    public void testAdd() {
        // Step 1: Load hibernate Core Profile
        // Configuration cfg = new Configuration();
        // cfg.configure();
        // Step 2: Create SessionFactory object
        // SessionFactory sessionFactory = cfg.buildSessionFactory();

        SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
        // Step 3: Use SessionFactory Establish session object
        Session session = sessionFactory.openSession();
        // Step 4: Open a transaction
        Transaction tx = session.beginTransaction();

        // Step 5: Write specific logic curd operation
        // Add functionality
        User user = new User();
        user.setUsername("Mr Li");
        user.setPassword("1234");
        user.setAddress("Wuhan");

        // call session Method implementation adds
        session.save(user);

        // Step 6: Submit a transaction
        tx.commit();
        // Step 7: Close resources
        session.close();
        sessionFactory.close();

    }

}

Second: Hibernate API Exercise

1. Create project (omit) 2. Import jar package (omit) 3. Entity class + its mapping file (omit)

4.Hibernate Core Profile

<?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>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql:///hibernate_test2</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    
    <!-- stay hibernate Configuration in Core Profile -->
    <property name="hibernate.current_session_context_class">thread</property>
    <!-- Put the map file in hibernate Among Core Profiles -->
    <mapping resource="cn/itcast/entity/User.cfg.xml"/>
    </session-factory>    
    </hibernate-configuration>

5.Hibernate related test code:

(1)HibernateDemo.java

package cn.itcast.hibernatetest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.entity.User;
import cn.itcast.utils.HibernateUtils;


public class HibernateDemo {

    @Test
    public void testSaveOrUpdate() {
        // 1.Call the tool class to get sessionFactory
        SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
        // 2.Obtain session
        Session session = sessionFactory.openSession();
        // 3.Open Transaction
        Transaction tx = session.beginTransaction();
        // 4.Add Action
        // User user = new User();
        // user.setUid(1);
        // user.setUsername("King First");
        // user.setPassword("12345");
        // user.setAddress("Apricot forest Erxiao");
        // session.save(user);

        // hold uid=1 Records username modify
        // User user = new User();
        // user.setUid(1);
        // user.setUsername("Hanmeimei");
        // session.save(user);To use update
        // session.update(user);

        // User user = session.get(User.class, 2);
        // user.setAddress("Xinglong Forestry Bureau");
        // // Entity class object is persistent, modified
        // session.saveOrUpdate(user);

        // User user = new User();
        // user.setUsername("rose");
        // user.setPassword("1314");
        // user.setAddress("Albania");
        // session.save(user);

        // User user = new User();
        // user.setUsername("jack");
        // user.setPassword("520");
        // user.setAddress("Korea");
        // session.save(user);

        User user = new User();
        user.setUsername("jack");
        user.setPassword("124");
        user.setAddress("china");
        session.save(user);

        // 5.Submit Transaction
        try {
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            // 6.close resource
            session.close();
            sessionFactory.close();
        }

    }

    @Test
    public void testDelete() {
        // 1.Create with Tool Class sessionFactory
        SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
        // 2.obtain session
        Session session = sessionFactory.openSession();
        // 3.Open Transaction
        Transaction tx = session.beginTransaction();
        // 4.Delete operation
        // First Delete Method
        // User user = session.get(User.class, 1);
        // session.delete(user);

        // Second Delete Method
        User user = new User();
        user.setUid(3);
        session.delete(user);

        // 5.Submit Transaction
        try {
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            // 6.close resource
            session.close();
            sessionFactory.close();
        }

    }

    @Test
    public void testUpdate() {
        // 1.Get in Tool Class sessionFactory
        SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
        // 2.obtain session
        Session session = sessionFactory.openSession();
        // 3.Open Transaction
        Transaction tx = session.beginTransaction();
        // 4.update operation(modify uid=2 Recorded username value)
        // 4.1 according to id query(If this is not present in the database id,Query is executed)
        User user = session.get(User.class, 2);
        // 4.2 To returned username Set the modified value inside the object
        user.setUsername("Modified value");
        // 4.3 call session Of update Method
        // Execution process: To user Found inside object uid Value, based on uid Modify
        session.update(user);
        // 5.Submit Transaction
        try {
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            // 6.close resource
            session.close();
            sessionFactory.close();
        }

    }

}

(2)HibernateQueryData.java

package cn.itcast.hibernatetest;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.entity.User;
import cn.itcast.utils.HibernateUtils;

public class HibernateQueryData {

    // Use SQLQuery object
    @Test
    public void testQuery() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // Establish SQLQuery object
            SQLQuery sqlQuery = session.createSQLQuery("select * from t_user");
            // Returned list Each part of the is in the form of an object
            sqlQuery.addEntity(User.class);
            // call SQLQuery Method inside...The guide pack is: import java.util.List;
            @SuppressWarnings("unchecked")
            List<User> list = sqlQuery.list();

            // Validation: When called SQLQuery Method: Returned list Collection, each part of which is an array structure by default
            for (User user : list) {
                System.out.println(user);
            }
            // List<Object[]> list = sqlQuery.list();
            //
            // for (Object[] objects : list) {
            // System.out.println(Arrays.toString(objects));
            // }
            // Submit Transaction
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();

        }
    }

    // Use Criteria object
    @Test
    public void testCriteria() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            // Establish criteria object
            Criteria criteria = session.createCriteria(User.class);
            @SuppressWarnings("unchecked")
            List<User> list = criteria.list();
            for (User user : list) {
                System.out.println(user);
            }
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }

    // Use query object
    @Test
    public void demoQuery() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = HibernateUtils.getSessionobject();
            // Open Transaction
            tx = session.beginTransaction();

            // 1 Establish Query object
            Query query = session.createQuery("from User");

            // 2 call query Method inside object gets result
            @SuppressWarnings("unchecked")
            List<User> list = query.list();

            // ergodic list Four sets: normal for,Enhance for,Iterators, list iterator
            // ergodic set Collection of two: Enhancement for,iterator
            // ergodic map Set two things: get all key,according to key obtain value; obtain key-value relationship
            for (User user : list) {
                System.out.println(user);
            }

            // Submit Transaction
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }
}

(3)HibernateSelect.java

package cn.itcast.hibernatetest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.entity.User;
import cn.itcast.utils.HibernateUtils;

public class HibernateSelect {

    // Transaction Specification Code
    @Test
    public void testTx() {
        Session session = null;
        Transaction tx = null;
        try {
            // Bound on local thread session
            session = HibernateUtils.getSessionobject();
            // Open Transaction
            tx = session.beginTransaction();

            // Add to
            User user = new User();
            user.setAddress("HUAFENG");
            user.setPassword("789");
            user.setUsername("Huahua");

            session.save(user);

            // Simulated things: java.lang.ArithmeticException: / by zero
            // 10/0 Data cannot be inserted at this time

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            // Below session Can't close, JUnit Closing will cause an error.You can insert data.
            // org.hibernate.SessionException: Session was already closed
            // org.hibernate.SessionException: Session was already closed
            // session.close();
        }

    }

    // Level 1 Cache Features
    @Test
    public void testDemo() {

        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;

        try {
            // 1.Call the tool class to get sessionFactory
            sessionFactory = HibernateUtils.getSessionFactory();
            // 2.Obtain session
            session = sessionFactory.openSession();

            // 3.Open Transaction
            tx = session.beginTransaction();
            // 4.Operation: Query
            User user = session.get(User.class, 5);

            user.setAddress("Front Room china,Now it is Harbin");
            session.update(user);

            // 5.Submit Transaction
            tx.commit();

        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            // 6.close resource
            session.close();
            sessionFactory.close();
        }

    }

    // Verify the existence of a first-level cache
    @Test
    public void testCasch() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.according to id=2 query
            // Execute the first get Method whether to query the database, whether to send statements
            User user1 = session.get(User.class, 2);
            System.out.println(user1);

            // 2.On the basis of id query
            // Execute the second get Method whether to query the database, whether to send statements
            // The result is!Only one query statement, two query results
            User user2 = session.get(User.class, 2);
            System.out.println(user2);

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }

}

Third: Hibernate's One-to-Many, Many-to-Many Fighting

1.Cn.itcast.entityInside the bag:

(1)Customer.java

package cn.itcast.entity;

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

public class Customer {
    // user id
    private Integer cid;

    // User Name
    private String custName;

    // User level
    private String custLevel;

    // User Source
    private String custSource;

    // Contact number
    private String custPhone;

    // Mobile phone
    private String custMobile;

    // Represents multiple contacts in a customer entity class, and multiple contacts in a customer
    // hibernate Require collection to represent more data, use set aggregate:
    // import java.util.HashSet;import java.util.Set;
    private Set<LinkMan> setLinkMan = new HashSet<LinkMan>();

    public Set<LinkMan> getSetLinkMan() {
        return setLinkMan;
    }

    public void setSetLinkMan(Set<LinkMan> setLinkMan) {
        this.setLinkMan = setLinkMan;
    }

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustLevel() {
        return custLevel;
    }

    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }

    public String getCustSource() {
        return custSource;
    }

    public void setCustSource(String custSource) {
        this.custSource = custSource;
    }

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }

    public String getCustMobile() {
        return custMobile;
    }

    public void setCustMobile(String custMobile) {
        this.custMobile = custMobile;
    }

}

Customer.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<!-- 1.Configuration Class and Table Correspondence
       class Label
       name Attribute: Full path to entity class
       table Property: Database table name -->
<class name="cn.itcast.entity.Customer" table="t_customer">
<id name="cid" column="cid">
<generator class="native"></generator>
</id>
<property name="custName" column="custName"></property>
<property name="custLevel" column="custLevel"></property>
<property name="custSource" column="custSource"></property>
<property name="custPhone" column="custPhone"></property>
<property name="custMobile" column="custMobile"></property>

<!-- Represents all contacts in the customer mapping file
     Use set Tag: represents all contacts
     set Inside the label is name Attribute: Attribute values are written in the client entity class, representing the contact's set Collection Name 
     reverse Property defaults: false Indicates no abandonment of maintenance
                    true Indicates abandonment of maintenance-->
<set name="setLinkMan" inverse="true">
<!-- One-to-many table with foreign keys
     hibernate Mechanisms: Maintain foreign keys in both directions, configure foreign keys on one and both sides
     column Property value: foreign key name
      -->
<key column="clid"></key>
<!-- All contacts of the customer, class Write full path of contact entity class inside -->
<one-to-many class="cn.itcast.entity.LinkMan"/>
</set>
</class>
</hibernate-mapping>

(2)LinkMan.java

package cn.itcast.entity;

public class LinkMan {
    // Contact number (primary key)
    private Integer lkm_id;

    // Contact Name
    private String lkm_name;

    // Contact Gender
    private String lmk_gender;

    // Contact Office Phone
    private String lkm_phone;

    // Represents all customers in the contact entity class, and a contact can only belong to one customer
    // Customer customer=new Customer();
    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Integer getLkm_id() {
        return lkm_id;
    }

    public void setLkm_id(Integer lkm_id) {
        this.lkm_id = lkm_id;
    }

    public String getLkm_name() {
        return lkm_name;
    }

    public void setLkm_name(String lkm_name) {
        this.lkm_name = lkm_name;
    }

    public String getLmk_gender() {
        return lmk_gender;
    }

    public void setLmk_gender(String lmk_gender) {
        this.lmk_gender = lmk_gender;
    }

    public String getLkm_phone() {
        return lkm_phone;
    }

    public void setLkm_phone(String lkm_phone) {
        this.lkm_phone = lkm_phone;
    }

}

LinkMan.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="cn.itcast.entity.LinkMan" table="t_linkman">
<id name="lkm_id" column="lkm_id">
<generator class="native"></generator>
</id>
<property name="lkm_name" column="lkm_name"></property>
<property name="lmk_gender" column="lmk_gender"></property>
<property name="lkm_phone" column="lkm_phone"></property>

<!-- Represents the customer to which the contact belongs
    name Attribute: because used in contact entity class customer Object Representation, Write customer Name
    class Attributes: customer Full Path
    column Attribute: Foreign key name -->
    <many-to-one name="customer" class="cn.itcast.entity.Customer" column="clid"></many-to-one>
</class>
</hibernate-mapping>

2. Inside the HibernateUtils package HibernateUtils.java Tool class, method to add session s bound by local threads

package cn.itcast.utils;

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

public class HibernateUtils {

    // Load core profile, static code block implementation
    static Configuration cfg = null;

    static SessionFactory sessionFactory = null;
    static {
        cfg = new Configuration();
        cfg.configure();
        sessionFactory = cfg.buildSessionFactory();
    }

    // Provides returns bound to the local thread session Method
    public static Session getSessionObject() {
        return sessionFactory.getCurrentSession();
    }

    // Provide Method Return sessionFactory
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void main(String[] args) {

    }
}

3.Hibernate Core Profile

<?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>
<!-- Part 1: Configuring database information, required -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_test3</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- Part Two: Configuration hibernate Information, optional -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Configure Database Dialect
    //Paging in mysql, keyword limit, can only be used in MySQL
    //Paging rownum in oracle Database
    //Let the hibernate framework recognize its own unique statements for different databases -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<!-- Part 3: To place a mapping file in a core configuration file, you must-->
<mapping resource="cn/itcast/entity/Customer.hbm.xml"/>
<mapping resource="cn/itcast/entity/LinkMan.hbm.xml"/>

<mapping resource="cn/itcast/manytomany/User.hbm.xml"/>
<mapping resource="cn/itcast/manytomany/Role.hbm.xml"/>


</session-factory>
</hibernate-configuration>

4.Hibernatetest package

(1)HibernateOnetoMany.java

package hibernatetest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.entity.Customer;
import cn.itcast.entity.LinkMan;
import cn.itcast.utils.HibernateUtils;


public class HibernateOnetoMany {

    // Demonstration:One-to-many Cascade Save
    @Test
    public void testUpdate() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // Add a customer, add a contact for this customer
            // 1 Create customer and contact objects
            Customer customer = new Customer();
            customer.setCustLevel("vip");
            customer.setCustMobile("8888");
            customer.setCustName("Acorn International");
            customer.setCustPhone("18345782345");
            customer.setCustSource("Shanghai");

            LinkMan linkman = new LinkMan();
            linkman.setLkm_name("Wang Xiaozhuo");
            linkman.setLkm_phone("173456379876");
            linkman.setLmk_gender("female");

            // 2 Represent all contacts at the customer and customers at the contact
            // Establish customer and contact object relationships
            // 2.1 Put Contact Objects in Customer Objects set Inside Collection
            customer.getSetLinkMan().add(linkman);
            // 2.2 Put customer in contact
            linkman.setCustomer(customer);

            // 3 Save to database
            session.save(customer);
            session.save(linkman);

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }

    // Demonstration:One-to-many Cascade Save
    @Test
    public void testAddDemo2() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            Customer customer = new Customer();
            customer.setCustLevel("ordinary");
            customer.setCustName("Ox");
            customer.setCustPhone("18932222237");
            customer.setCustSource("Beijing");

            LinkMan linkman = new LinkMan();
            linkman.setLkm_name("Chen Xiaoqiao");
            linkman.setLkm_phone("15024324567");
            linkman.setLmk_gender("female");

            customer.getSetLinkMan().add(linkman);
            // Without this sentence, linkman.setCustomer(customer);Execute only t_customer Table insert Sentence
            // Add it and session.save(linkman);,be t_linkman New data added to the table (Chen Xiaoqiao) will be added
            linkman.setCustomer(customer);

            // save() Save it!
            session.save(customer);
            session.save(linkman);

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            // sessionFactory.close();
            // session.close();
        }
    }

    // Demo: One-to-many cascade deletion
    @Test
    public void testDeleteDemo() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.according to id Query Customer Objects
            Customer customer = session.get(Customer.class, 12);
            // 2.Call Delete Method
            session.delete(customer);
            // 3.Submit Transaction
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            // sessionFactory.close();
        }
    }

    // Demo: One-to-many modifications
    @Test
    public void testUpdateDemo() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            // 1.according to id Query contacts based on id Query Customer
            Customer customer1 = session.get(Customer.class, 3);
            LinkMan linkman1 = session.get(LinkMan.class, 1);
            // 2.Setting persistent object values
            // i.Put Contacts in Customers
            customer1.getSetLinkMan().add(linkman1);
            // ii.Put the customer in the contact
            linkman1.setCustomer(customer1);
            // 3.Submit Transaction
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            // sessionFactory.close();
        }

    }

}

(2)HibernateManytoMany.java

package hibernatetest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.manytomany.Role;
import cn.itcast.manytomany.User;
import cn.itcast.utils.HibernateUtils;


public class HibernateManytoMany {
    // Demo Maintenance Third Table
    @Test
    public void testTable1() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // Give a user a role
            // 1.query
            User user1 = session.get(User.class, 2);
            Role role1 = session.get(Role.class, 2);
            // 2.discharge
            user1.getSetRole().add(role1);

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            // sessionFactory.close();
        }
    }

    // Demo: Maintain the third table
    @Test
    public void testTable2() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // Let a user not have a role
            User user2 = session.get(User.class, 2);
            Role role2 = session.get(Role.class, 3);

            // Remove roles from users
            user2.getSetRole().remove(role2);
            // Submit Transaction
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            // sessionFactory.close();
        }

    }

    // Demo: Many-to-Many Cascade Delete
    @Test
    public void testSave() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // Add two users and add two roles for each user
            // 1.create object
            User user3 = new User();
            user3.setUser_name("youth");
            user3.setUser_password("8766899");

            User user4 = new User();
            user4.setUser_name("mary");
            user4.setUser_password("456");

            Role role3 = new Role();
            role3.setRole_name("pig");
            role3.setRole_memo("Pink");

            Role role4 = new Role();
            role4.setRole_name("secretary");
            role4.setRole_memo("secretary");

            Role role5 = new Role();
            role5.setRole_name("Security staff");
            role5.setRole_memo("Security staff");

            // 2.Build relationships and put roles within users
            user3.getSetRole().add(role3);
            user3.getSetRole().add(role4);

            user4.getSetRole().add(role4);
            user4.getSetRole().add(role5);

            // 3.Preservation
            session.save(user3);
            session.save(user4);

            // 4.Submit Transaction
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            // sessionFactory.close();
        }
    }

    // Demo: Multi-to-Multi Cascade Save
    @Test
    public void testDelete() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            User user5 = session.get(User.class, 1);
            session.delete(user5);
            // Submit Transaction
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            // sessionFactory.close();
        }
    }
}

5.Cn.itcast.manytomanypackage

(1)Role.java

package cn.itcast.manytomany;

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

public class Role {

    private Integer role_id;

    private String role_name;

    private String role_memo;

    // Multiple customers in a role
    private Set<User> setUser = new HashSet<User>();

    public Set<User> getSetUser() {
        return setUser;
    }

    public void setSetUser(Set<User> setUser) {
        this.setUser = setUser;
    }

    public Integer getRole_id() {
        return role_id;
    }

    public void setRole_id(Integer role_id) {
        this.role_id = role_id;
    }

    public String getRole_name() {
        return role_name;
    }

    public void setRole_name(String role_name) {
        this.role_name = role_name;
    }

    public String getRole_memo() {
        return role_memo;
    }

    public void setRole_memo(String role_memo) {
        this.role_memo = role_memo;
    }

}

Role.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<!-- 1.Configuration Class and Table Correspondence
    class Label
    name Attribute: Full path to entity class
    table Property: Database table name -->
<class name="cn.itcast.manytomany.Role" table="t_role">
<id name="role_id" column="role_id">
<generator class="native"></generator>
</id>
<property name="role_name" column="role_name"></property>
<property name="role_memo" column="role_memo"></property>
<!-- Represents all users in a role, using set Label -->
<set name="setUser" table="user_role">
<!-- Role Foreign Key in Third Table -->
<key column="roleid"></key>
<many-to-many class="cn.itcast.manytomany.User" column="userid"></many-to-many>
</set>
</class>
</hibernate-mapping>

(2)User.java

package cn.itcast.manytomany;

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

public class User {

    private Integer user_id;

    private String user_name;

    private String user_password;

    // A user can have multiple roles
    private Set<Role> setRole = new HashSet<Role>();

    public Set<Role> getSetRole() {
        return setRole;
    }

    public void setSetRole(Set<Role> setRole) {
        this.setRole = setRole;
    }

    public Integer getUser_id() {
        return user_id;
    }

    public void setUser_id(Integer user_id) {
        this.user_id = user_id;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getUser_password() {
        return user_password;
    }

    public void setUser_password(String user_password) {
        this.user_password = user_password;
    }

}

User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="cn.itcast.manytomany.User" table="t_user">
<id name="user_id" column="user_id">
<generator class="native"></generator>
</id>
<property name="user_name" column="user_name"></property>
<property name="user_password" column="user_password"></property>
<!--Represent all roles within the user, using the set tag
    Name property: role set collection name
    Table property: third table name -->
<set name="setRole" table="user_role" cascade="save-update,delete">
<!--Configuration inside key tag
    Configure the name of the foreign key in the third table for the current mapping file
     -->
<key column="userid"></key>
<!--class label: full path to role entity class
    Columumn tag: Role in the third table foreign key name-->
<many-to-many class="cn.itcast.manytomany.Role" column="roleid"></many-to-many>
</set>
</class>
</hibernate-mapping>

Article 4: Exercises on HQL, QBC, Query, Retrieval Strategy, Mass Grabbing, etc.

1.Cn.itcast.entitypackage

(1)Cutomer.java

package cn.itcast.entity;

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

public class Customer {
    private Integer cid;

    private String custName;

    private String custLevel;

    private String custSource;

    private String custPhone;

    private String custMobile;

    // Represents multiple contacts in a customer entity class, and multiple contacts in a customer
    private Set<LinkMan> setLinkMan = new HashSet<LinkMan>();

    public Set<LinkMan> getSetLinkMan() {
        return setLinkMan;
    }

    public void setSetLinkMan(Set<LinkMan> setLinkMan) {
        this.setLinkMan = setLinkMan;
    }

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustLevel() {
        return custLevel;
    }

    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }

    public String getCustSource() {
        return custSource;
    }

    public void setCustSource(String custSource) {
        this.custSource = custSource;
    }

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }

    public String getCustMobile() {
        return custMobile;
    }

    public void setCustMobile(String custMobile) {
        this.custMobile = custMobile;
    }

}

Customer.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    <class name="cn.itcast.entity.Customer" table="t_customer">
    <id name="cid" column="cid">
    <generator class="native"></generator>
    </id>
    <property name="custName" column="custName"></property>
    <property name="custLevel" column="custLevel"></property>
    <property name="custSource" column="custSource"></property>
    <property name="custPhone" column="custPhone"></property>
    <property name="custMobile" column="custMobile"></property>
    <!-- Represents all contacts in the customer mapping file 
            Use set Tags represent all contacts
            set Inside the label is name Attributes:
                 Attribute values written in the customer entity class represent the contact's set Collection Name
                 
             inverse Property defaults: false Do not abandon relationship maintenance
                            true Indicates abandonment of relationship maintenance
        -->
    <set name="setLinkMan" batch-size="10">
    <!-- One-to-many table with foreign keys
                hibernate Mechanisms: Maintain foreign keys in both directions, configure foreign keys on one and both sides    
                column Property value: foreign key name
             -->
    <key column="clid"></key>
    <one-to-many class="cn.itcast.entity.LinkMan"/>
    </set>
    </class>
    </hibernate-mapping>

(2).LinkMan.java

package cn.itcast.entity;

public class LinkMan {
    private Integer lkm_id; // Contact Number(Primary key)

    private String lkm_name;// Contact Name

    private String lkm_gender;// Contact Gender

    private String lkm_phone;// Contact Office Phone

    // Represents the customer in the contact entity class, and a contact can have only one customer
    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Integer getLkm_id() {
        return lkm_id;
    }

    public void setLkm_id(Integer lkm_id) {
        this.lkm_id = lkm_id;
    }

    public String getLkm_name() {
        return lkm_name;
    }

    public void setLkm_name(String lkm_name) {
        this.lkm_name = lkm_name;
    }

    public String getLkm_gender() {
        return lkm_gender;
    }

    public void setLkm_gender(String lkm_gender) {
        this.lkm_gender = lkm_gender;
    }

    public String getLkm_phone() {
        return lkm_phone;
    }

    public void setLkm_phone(String lkm_phone) {
        this.lkm_phone = lkm_phone;
    }

}

LinkMan.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    <class name="cn.itcast.entity.LinkMan" table="t_linkman">
    <id name="lkm_id" column="lkm_id">
    <generator class="native"></generator>
    </id>
    <property name="lkm_name" column="lkm_name"></property>
    <property name="lkm_gender" column="lkm_gender"></property>
    <property name="lkm_phone" column="lkm_phone"></property>
   
    <!-- Represents the customer to which the contact belongs 
            name Attribute: because used in contact entity class customer Object Representation, Write customer Name
            class Attributes: customer Full Path
            column Attribute: Foreign key name
        -->
    <many-to-one name="customer" class="cn.itcast.entity.Customer" column="clid"></many-to-one>
    </class>
    </hibernate-mapping>

2.utils package (same as above)

HibernateUtils.java

package ustils;

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

public class HibernateUtils {

    static Configuration cfg = null;

    static SessionFactory sessionFactory = null;
    static {
        cfg = new Configuration();
        cfg.configure();
        sessionFactory = cfg.buildSessionFactory();
    }

    public static Session getSessionobject() {
        return sessionFactory.getCurrentSession();
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void main(String[] args) {

    }
}

3.Hibernate Core Profile

<?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>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql:///hibernate_test4</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.current_session_context_class">thread</property>
    
    <mapping resource="cn/itcast/entity/Customer.hbm.xml"/>
    <mapping resource="cn/itcast/entity/LinkMan.hbm.xml"/>
    </session-factory>
    </hibernate-configuration>

4.Cn.itcast.hibernantetestpackage

(1)HibernateDemo.java

package cn.itcast.hibernantetest;

import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.entity.Customer;
import cn.itcast.entity.LinkMan;
import ustils.HibernateUtils;

public class HibernateDemo {

    // Demo Object Navigation Query
    @Test
    public void testSelect1() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;

        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.query cid=1 Customer
            Customer customer = session.get(Customer.class, 1);
            // 2.Query all contacts in this customer again(At this point, get set Collection, no statement sent)
            Set<LinkMan> linkman = customer.getSetLinkMan();

            // Sent statement
            System.out.println(linkman.size());

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }

    // Demonstrate retrieval strategies
    @Test
    public void testSelect2() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;

        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // according to cid=1 Customer
            // implement get Whether to send after method sql Sentence
            // call get Method Send Immediately sql Statement Query Database
            // Customer customer = session.get(Customer.class, 1);
            // System.out.println(customer.getCid());
            /*
             * 1 After calling the load method, the sql statement (1) will not be sent immediately to return an object with an id-only value
             * 
             * 2 Send statements only when you get other values in the object that are not IDS
             */
            Customer customer = session.load(Customer.class, 1);
            System.out.println(customer.getCid());
            System.out.println(customer.getCustName());

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }

    // Demonstrate batch capture
    @Test
    public void testSelect3() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;

        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // Query all customers
            Criteria criteria = session.createCriteria(Customer.class);
            // Get all the contacts in each customer
            List<Customer> list = criteria.list();

            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
                // All contacts in each customer
                Set<LinkMan> setlinkman = customer.getSetLinkMan();
                for (LinkMan linkMan : setlinkman) {
                    System.out.println((linkMan.getLkm_id() + "::" + linkMan.getLkm_name()));
                }
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }
}

(2)HibernateHQL.java

package cn.itcast.hibernantetest;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.entity.Customer;
import ustils.HibernateUtils;

public class HibernateHQL {

    // Demo Query All
    @Test
    public void testSelect1() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.Establish query object
            Query query = session.createQuery("from Customer");
            // 2.Call method to get result
            List<Customer> list = query.list();
            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
            }

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }

    }

    // Demonstration Conditions Query
    @Test
    public void testSelect2() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.Establish query object
            // SELECT *FROM t_customer WHERE cid=? AND custName=?
            Query query = session.createQuery("from Customer c where c.cid=? and c.custName=?");
            // 2.Set Conditions
            // To?Set value inside
            // setParameter Method Two Parameters
            // First parameter: int What is the type?Location,?Position starts at 0
            // Second parameter: specific parameter value
            // Set first?value
            query.setParameter(0, 1);
            // Set the second one?value
            query.setParameter(1, "Baidu");
            // 3.Call method to get result
            List<Customer> list = query.list();
            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
            }

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }

    }

    // Demonstration Conditions Query-Fuzzy Query
    @Test
    public void testSelect3() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.Establish query object
            Query query = session.createQuery("from Customer c where c.custName like ?");
            // 2.Set up?Value of
            query.setParameter(0, "%Tie%");
            // 3.Call method to get result
            List<Customer> list = query.list();
            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }

    }

    // Demo: Sort Query
    @Test
    public void testSelect4() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.Establish query object
            Query query = session.createQuery("from Customer order by cid desc");
            // 2.Call method to get result
            List<Customer> list = query.list();
            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }

    }

    // Demonstration:Paging Query
    @Test
    public void testSelect5() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.Establish query object
            // Write Query All Statements
            Query query = session.createQuery("from Customer");
            // 2.Set Paging Data
            // 2.1.Set start position
            query.setFirstResult(3);
            // 2.2.Set the number of records per page
            query.setMaxResults(3);
            // 3.Call method to get result
            List<Customer> list = query.list();
            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }

    }

    // Demonstration:Projection Query
    @Test
    public void testSelect6() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.Establish query object
            Query query = session.createQuery("select custLevel from Customer");
            // 2.Call method to get result
            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();
        }

    }

    // Demonstration:Use of aggregate functions
    @Test
    public void testSelect7() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.Establish query object
            Query query = session.createQuery("select count(*) from Customer");
            // 2.Call method to get result
            // query Object has methods inside it, returning the object form directly
            Object obj = query.uniqueResult();
            // Return int type
            // int count=(int)obj;

            // First put object Become long Type, then become int type
            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();
        }

    }

}

(3)HibernateQBC.java

package cn.itcast.hibernantetest;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import cn.itcast.entity.Customer;
import ustils.HibernateUtils;


public class HibernateQBC {

    // Demo: Query All
    @Test
    public void testSelect1() {

        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.create object
            Criteria criteria = session.createCriteria(Customer.class);
            // 2.Call method to get result
            List<Customer> list = criteria.list();
            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }

    }

    // Demo: Conditional Query
    @Test
    public void testSelect2() {

        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.Establish criteria object
            Criteria criteria = session.createCriteria(Customer.class);
            // 2.Use criteria Method inside object sets condition value
            // use first add Method to set a condition value
            // stay add Class methods are used inside methods to implement conditional settings
            // Be similar to cid=?
            // criteria.add(Restrictions.eq("cid", 1));
            // criteria.add(Restrictions.eq("custName", "Maserati"));
            // Above is eq,Here are like
            criteria.add(Restrictions.like("custName", "%hundred%"));
            // 3.Call method to get result
            List<Customer> list = criteria.list();

            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }

    }

    // Demo: Sort Query
    @Test
    public void testSelect3() {

        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.create object
            Criteria criteria = session.createCriteria(Customer.class);
            // 2.Set which attribute to sort, set the collation
            criteria.addOrder(Order.desc("cid"));
            // 3.Call the method and get the result
            List<Customer> list = criteria.list();
            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }

    }

    // Demo: Paging Query
    @Test
    public void testSelect4() {

        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.create object
            Criteria criteria = session.createCriteria(Customer.class);
            // 2.Set Paging, Starting and Number of Records
            criteria.setFirstResult(3);
            criteria.setMaxResults(3);
            // 3.Call method to get result
            List<Customer> list = criteria.list();
            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }

    }

    // Demo: Statistical Query
    @Test
    public void testSelect5() {

        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.create object
            Criteria criteria = session.createCriteria(Customer.class);
            // 2.Setup Operation
            criteria.setProjection(Projections.rowCount());
            // 3.Call method to get result
            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();
        }

    }

    // Demo: Offline Query
    @Test
    public void testSelect6() {

        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.create object
            // Criteria criteria = session.createCriteria(Customer.class);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);
            // 2.Final Execution Required session
            Criteria criteria = detachedCriteria.getExecutableCriteria(session);
            List<Customer> list = criteria.list();
            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }

    }

}

(4)HibernateManyTable.java

package cn.itcast.hibernantetest;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import ustils.HibernateUtils;

public class HibernateManyTable {

    // Demonstration hql Inner Join Query (2)
    @Test
    public void testSelect1() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // Internally connected list Returned as an array; urgently connected inside and outside list What you put back is the form of the object
            // Query query = session.createQuery("from Customer c inner join
            // c.setLinkMan");
            // List list = query.list();

            Query query = session.createQuery("from Customer c inner join fetch c.setLinkMan");
            List list = query.list();

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }

    // Demonstration hql Outer Join Query (3 types)
    @Test
    public void testSelect2() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // Left Outer Connected list Returns the form of an array; urgently left-outer connected list What you put back is the form of the object
            // Query query = session.createQuery("from Customer c left outer
            // join c.setLinkMan");
            // List list = query.list();

            // Query query = session.createQuery("from Customer c left outer
            // join fetch c.setLinkMan");
            // List list = query.list();

            // Right Outer Connection, No Urgent Right Outer Connection
            Query query = session.createQuery("from Customer c right outer join fetch c.setLinkMan");
            List list = query.list();

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }
}

Hibernate Definition Statement:

Hibernate is an open source object relational mapping framework. It encapsulates JDBC in a very lightweight object package. It maps POJO to database tables. Hibernate is a fully automated orm framework. Hibernate can automatically generate and execute SQL statements, enabling Java programmers to manipulate databases with object programming thinking as they like.Hibernate can be used in any JDBC application, either in Java client programs or in Servlet/JSP Web applications. Most revolutionarily, Hibernate can replace CMP in the JaveEE architecture where EJB is applied to accomplish the task of data persistence.-------From Baidu Encyclopedia

Topics: Java Session Hibernate xml