Hibernate framework using basic learning

Hibernate Framework Overview

1 Introduction

  • Hibernate object-relational mapping framework is an open source
  • It had a very lightweight JDBC object package
  • It POJO mapping relationship with a database table, is a fully automated framework orm
  • hibernate automatically generate SQL statements can be executed automatically, so that Java programmers use object programming thinking to manipulate the database can be arbitrary .
  • Hibernate can be used in any occasion using JDBC, Java can be used in both client program can also be used in Servlet / JSP Web application
  • ORM persistence layer frame

ORM: Object Relational Mapping (Object-relational mapping).
It refers to the establishment of a mapping between Java objects in a relational database table, so that the operator can manipulate objects on tables in the database.

2. advantage

  • JDBC database access code to be lightweight package, it simplifies the data access layer tedious repetitive codes, reduced memory consumption, speed up the operating efficiency
  • JDBC is a basic mainstream persistence framework, to a large extent simplifies the DAO layer coding work
  • Performance is very good, better flexibility mapping, support for multiple relational databases, complex relationships one to one, one to many, many to many
  • Scalability , source code and open API, when the function itself is not enough, self-encoding can be extended

The basic use of Hibernate

1. Import jar package

Then import the jar before we start to look at the directory structure hibernate

  • Documentation Hibernate development, documentation
  • lib Hibernate development of a jar
    - required
    Hibernate dependencies must be developed
    - optional
    optional jar package Hibernate development
  • project
    reference provided by the Hibernate project

In addition to the above-described hibernate jar package must be imported, we also need to import database driver package, connection pool jar package.

2. Profiles

  1. To use the hibernate we first need to configure the kernel configuration file hibernate.cfg.xml
<!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.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///hibernate?useSSL=false&amp;serverTimezone=UTC</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>
        <!-- 配置Hibernate的方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <!-- 打印SQL -->
        <property name="hibernate.show_sql">true</property>
        <!-- 格式化SQL -->
        <property name="hibernate.format_sql">true</property>
        <!-- 自动创建表 -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!--加载映射文件-->
        <mapping resource="com/thinmoon/domain/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

For hibernate.hbm2ddl.auto a parsing various operations

Attributes meaning
none Do not use hibernate automatically build the table
create If you already have a database table, delete the original table, re-create, if there is no table, New Table
create-drop If you already have a table, delete the original table, perform the operation, delete the table in the database. If there is no table, create a new, ran out to remove the table. Finally, a database table is not in order to do testing. When the sessionFactory also close off will be effective
update If you have a database table, use the original table, if there is no table, create a new table
to update the table structure, if the column does not create a new one when
validate If there is no table, the table will not be created. Only use any original database tables
check whether the maps and tables structure consistent inconsistency will error
  1. The mapping between a configuration file, we know hibernate allows us to use object-oriented approach to manipulate the database, so we have to establish the mapping between classes and tables to make hibernate right to manipulate, which we generally configuration file format is named class name .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="com.thinmoon.domain.Customer" table="customer">
            <!--建立主键映射关系-->
            <id name="cust_id" column="cust_id">
                <!--设置主键增长方式-->
                <generator class="native"/>
            </id>
            <!--建立属性之间的映射关系-->
            <property name="cust_name" column="cust_name" />
            <property name="cust_source" column="cust_source"/>
            <property name="cust_industry" column="cust_industry"/>
            <property name="cust_level" column="cust_level"/>
            <property name="cust_phone" column="cust_phone"/>
            <property name="cust_mobile" column="cust_mobile"/>
        </class>
    </hibernate-mapping>

    Customer class:

    @Setter @Getter
    public class Customer {
    
        long cust_id;
        String cust_name;
        String cust_source;
        String cust_industry;
        String cust_level;
        String cust_phone;
        String cust_mobile;
    }

3. manipulate database

Let's look a little demo:

public class HibernateTest {
    @Test
    public void testM(){
        //1.加载配置文件 hibernate.cfg.xml
        Configuration configure = new Configuration().configure();
        //2.创建sessionFactory 相当于jdbc的连接池
        SessionFactory sessionFactory = configure.buildSessionFactory();
        //3.获取session连接对象 相当于jdbc中的连接对象
        Session session = sessionFactory.openSession();

        Customer customer = new Customer();
        customer.setCust_name("thinmoon");
        customer.setCust_level("2");

        session.save(customer);

        session.close();
        sessionFactory.close();
    }
}

Next we were doing an explanation of the above objects:

Configuration

Hibernate is an object Configuration configuration, action is Hibernate configuration, and it be started . Hibernate during startup, the first instance of the class Configuration position location mapping document, reads the configuration, and then create a SessionFactory. Although Configuration class throughout the Hibernate project only plays a small role, but it is the first object encountered when starting hibernate. By this object to load it inside the configuration, the data content inside or get to work behind.
effect:

  1. Load core configuration file, which can be the core configuration file xml form, it can be in the form of properties

    • The core profile is a properties file name: hibernate.properties
    configuration cfg = new configuration()
    • Core configuration file is an xml name: the hibernate.cfg.xml
    configuration cfg = new configuration();
    cfg.config()
  2. Loading map file

    There is no way to load the properties file mapping, you can load map file by config

    configuration.addResource("映射文件的全路径");

    xml can be configured directly in the configuration file.

SessionFactory

SessionFactory interface is responsible for initializing Hibernate, and is responsible for creating Session objects. Note that SessionFactory not lightweight, because under normal circumstances, a project usually requires only a SessionFactory is enough. When the need to operate a plurality of databases, each SessionFactory can specify a database. SessionFactory
internal maintenance of the connection pool Hibernate and Hibernate second-level cache, a project to create a just on the line, because there are connection pool, usually create a connection pool can be.

After hiberante5.0 comes with internal connection pool if we want to require additional configuration using a third-party connection pool, c3p0 following is an example of the configuration (should hibernate for c3p0 support better). First, we need to import the jar package jar package has c3p0 in the lib directory in the optional hibernate in. Followed by the configuration in hibernate.cfg.xml.

<!--配置c3p0-->

        <property name="connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
        <!--在连接池中可用的数据库连接的最少数目 -->
        <property name="c3p0.min_size">5</property>
        <!--在连接池中所有数据库连接的最大数目  -->
        <property name="c3p0.max_size">20</property>
        <!--设定数据库连接的过期时间,以秒为单位,
        如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
        <property name="c3p0.timeout">120</property>
        <!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
        <property name="c3p0.idle_test_period">3000</property>

Since we said above, a project generally as long as a SessionFactory so we will need a special tool to extract it out of the class:

public class HibernateUtil {
    public static final SessionFactory sessionFactory;
    static {
        //1.加载配置文件 hibernate.cfg.xml
        Configuration configure = new Configuration().configure();
        //2.创建sessionFactory 相当于jdbc的连接池
        sessionFactory = configure.buildSessionFactory();

    }
    public static Session openSession(){
        //3.获取session连接对象 相当于jdbc中的连接对象
        Session session = sessionFactory.openSession();
        return session;
    }
}
Session

Representatives of objects hibernate session is connected to the database, interacting with the database bridge through which to complete the database with the additions and deletions to change search of work

CRUD using the session were very simple:

method Code Explanation
preservation method save(Object obj)
Query methods get(T.class,id)
load(T.class,id)
GET (T.class, the above mentioned id)
2. After the query returns the real object itself
3. There is no query to the specified id, returns a null

load (T.class, id)
returns after 1 query is a proxy object, use a third-party proxy mechanism, javassist.jar
2. no query results directly to an exception report
modify void update(Object obj) Directly create objects to modify, if not specified other fields, other fields will be set to null.
To modify the recommended first record and then modify the object after check out
delete void delete(Object obj) Directly create deleted objects, does not support cascading deletes
and then delete the following query suggestions, support cascade delete
Save or update void saveOrUpdate(Object obj) Id is not set, the operation is saved
set id is a modification of the operation, if id is not set, it will error
All inquiries Query query = session.createQuery("from Customer");
List list = query.list()
Use HQL way
HQL: Hibernate Query Language query language for object-oriented

demo:

public class HibernateTest {
    @Test
    public void testSave(){
        Session session = HibernateUtil.openSession();
        Transaction transaction = session.beginTransaction();
        Customer customer = new Customer();
        customer.setCust_name("thinmoon111");
        customer.setCust_level("3");

        session.save(customer);
        transaction.commit();
        session.close();

    }

    @Test
    public void testDelete(){
        Session session = HibernateUtil.openSession();
        Transaction transaction = session.beginTransaction();

        Customer customer = session.get(Customer.class, 1L);
        System.out.println(customer);
        session.delete(customer);

        transaction.commit();
        session.close();

    }

    @Test
    public void testUpdate(){
        Session session = HibernateUtil.openSession();
        Transaction transaction = session.beginTransaction();

        Customer customer = session.get(Customer.class, 2L);
        System.out.println(customer);
        customer.setCust_level("10");
        session.update(customer);

        transaction.commit();
        session.close();

    }

    @Test
    public void testHQL(){
        Session session = HibernateUtil.openSession();
        Transaction transaction = session.beginTransaction();

        Query query = session.createQuery("from com.thinmoon.domain.Customer");
        List<Customer> list = query.list();
        for (Customer c: list) {
            System.out.println(c);
        }

        transaction.commit();
        session.close();

    }

}

induction

Profile hibernate.cfg.xml

<!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.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///hibernate?useSSL=false&amp;serverTimezone=UTC</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">15160673718wen</property>
        <!-- 配置Hibernate的方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <!-- 打印SQL -->
        <property name="hibernate.show_sql">true</property>
        <!-- 格式化SQL -->
        <property name="hibernate.format_sql">true</property>
        <!-- 自动创建表 -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!--配置c3p0-->

        <property name="connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
        <!--在连接池中可用的数据库连接的最少数目 -->
        <property name="c3p0.min_size">5</property>
        <!--在连接池中所有数据库连接的最大数目  -->
        <property name="c3p0.max_size">20</property>
        <!--设定数据库连接的过期时间,以秒为单位,
        如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
        <property name="c3p0.timeout">120</property>
        <!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
        <property name="c3p0.idle_test_period">3000</property>

        <!--添加映射文件-->
        <mapping resource="com/thinmoon/domain/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Guess you like

Origin www.cnblogs.com/ThinMoon/p/12482562.html