Detailed Hibernate Basics

1. Hibernate framework
        Hibernate is an open source object-relational mapping framework. It encapsulates JDBC with very lightweight objects. It establishes a mapping relationship between POJO classes and database tables. It is a
    fully automatic ORM framework. Hibernate can Automatically generate SQL statements and execute them automatically. Hibernate can be applied to any occasion using DBC, either in Java client programs
    or in Servlet/JSP web applications. Hibernate download orm, jar package official website: https://hibernate.org/orm/releases/
Second, ORM (Object Relational Mapping) model framework
        is used to realize the conversion between data of different type systems in object-oriented programming languages. Object Relational Mapping is produced with the development of object-oriented software development methods. The object-oriented
    development method is the mainstream development method today, and the relational database is the mainstream data storage system for permanently storing data in the application environment. Objects and relational data are two representations of business
    entities. Business entities are represented as objects in memory and relational data in the database. There are associations and inheritance relationships between objects in memory, while in the database, relational data cannot directly express many-to-many
    associations and inheritance relationships. Therefore, the ORM system generally exists in the form of middleware, which mainly realizes the mapping of program objects to relational database data.
Three, Hibernate configuration file
    1. Mapping file
        The mapping configuration file is mainly used to describe the mapping relationship between entity classes and data tables. The location should be in the same package as the entity class. Name: classname.hbm.xml

      <hibernate-mapping>
            <class name="*.*.*" table="t_customer" catalog="***">
                <id name="id" column="c_id">
                    <generator class="identity" />
                </id>
                
                <property name="name" column="c_name" length="20" />
                
                <set name="orders" inverse="false" cascade="save-update">
                    <key column="c_customer_id" />
                </set>
            </class>
        </hibernate-mapping>

        (1) The package name is uniformly declared, so that the full name of the class does not need to be written in <class>.
        (2) About the <class> tag configuration
            name attribute: the full name of the class. The name of the
            table table can be omitted. At this time, the name of the table is the same as the class name. Catalog
            attribute: the database name can be omitted. If omitted, refer to the core configuration file. The library name in the url path
        (3) Regarding the <id> tag, <id> is used to establish the mapping between the attributes in the class and the primary key in the table.
            name attribute name in the class
            column The primary key name in the table column It can also be omitted, then the column name is consistent with the attribute name in the class
            length field length
            type attribute specified type
            <generator> It mainly describes the primary key generation strategy.
        (4) Regarding the <property> tag, it describes the mapping relationship between the attributes in the class and the non-primary keys in the table.
    2. The core configuration file
        mainly contains information related to connecting to the database, hibernate related configuration, etc. Location: Create one in the project root directory. Name: hibernate.cfg.xml
        can be configured according to the information under the hibernate.properties file

<hibernate-configuration>
            <session-factory>
                <!-- 配置关于数据库连接的四个项 driverClass url username password -->
                <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
                <property name="hibernate.connection.url">jdbc:mysql:///**</property>
                <property name="hibernate.connection.username">***</property>
                <property name="hibernate.connection.password">***</property>

                <!-- Set connection provider --> 
                < property name ="hibernate.connection.provider_class" > org.hibernate.c3p0.internal.C3P0ConnectionProvider </ property > 
                <!-- c3p0 connection pool configuration --> 
                < property name ="hibernate.c3p0.max_size" > 20 </ property >  <!-- Maximum connection pool --> 
                < property name ="hibernate.c3p0.min_size" > 5 </ property >  <!-- Minimum number of connections- -> 
                <property name="hibernate.c3p0.timeout">120</property> <!-- 超时 -->
                <property name="hibernate.c3p0.idle_test_period">3000</property> <!-- 空闲连接 -->

                <!-- The sql sent to the database can be displayed --> 
                < property name ="hibernate.show_sql" > true </ property > 
                <!-- Format sql --> 
                < property name ="hibernate.format_sql" > true </ property >

                <!-- hibernate的方言 -->
                <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

                <!-- Auto create table --> 
                < property name ="hibernate.hbm2ddl.auto" > create </ property >

                <!-- Used to set the transaction commit method --> 
                < property name ="hibernate.connection.autocommit" > false </ property >

                <!-- The location of the mapping file for configuring hibernate --> 
                < mapping resource =".././*.hbm.xml"  />
                
            </session-factory>
        </hibernate-configuration>    

   Note: Whether it is a mapping file or a core configuration file, it must be constrained in the xml file. Take 3.0.dtd as an example:

 <!DOCTYPE hibernate-configuration PUBLIC
           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

       The location is: \project\etc\hibernate.properties under the jar package of hibernate
4. Hibernate working principle:
    1. Read and parse the hibernate.cfg.xml configuration file through Configuration().configure();
    2. The parsing mapping information is read from <mappingresource="xx/xx/xxx.hbm.xml"/> in hibernate.cfg.xml.
    3. Get sessionFactory through config.buildSessionFactory();.
    4.sessionFactory.openSession(); Get session.
    5.session.beginTransaction(); Start the transaction.
    6.session.getTransaction().commit(); Commit transaction
    7. Close session;
5. Hibernate persistence class and primary key generation strategy
    The primary key generation strategy that can be set in hbm.xml is as follows:
    Primary key generator Description
    increment Surrogate primary key. A variable maintained by hibernate that is automatically incremented each time a primary key is generated. Problem: If multiple applications access a database, each application maintains its own primary key. At this point the primary key may conflict. Not recommended.
    identity surrogate primary key. The table identifier is generated by the underlying database. The condition is that the database supports autogrow data types. For example: MySQL's self-incrementing primary key, oracle does not support the automatic generation of primary keys. If the database supports auto-increment, it is recommended to use it.
    sequence surrogate primary key. Hibernate generates identifiers based on the underlying database sequence. The condition is that the database supports the sequence. Such as oracle sequence. Recommended if the database supports sequences.
    native surrogate primary key. The identity, sequence, and hilo are automatically selected according to the underlying database. Since the control of the generation of the primary key strategy is controlled by hibernate, it is not recommended.
    uuid Surrogate primary key. Hibernate uses a 128-bit UUID algorithm to generate identifiers. The algorithm is capable of generating unique string identifiers in a network environment. This strategy can guarantee the uniqueness of the generated primary key, and provides the best database insert performance and database platform independence. recommended.
    assigned natural primary key. It is the responsibility of the java program to generate the identifier. Not recommended.
Six, Hibernate persistent object state
    1. Transient state: also known as temporary state or free state, it generally refers to our new object, it does not exist OID, has nothing to do with the hibernate session, there is no record in the database. After it is used
    , it will be directly recycled by the JVM, and it is only used for information carrying.
    Simply put: no OID is not associated with the information in the database and is not within the scope of session management.
    2. Persistent state: Within the scope of hibernate session management, it has the characteristics of persistent identification OID, which is persistent until the transaction is not committed. When it changes, hibernate
    can detect it.
    Simply put: there are OIDs managed by the session, there may or may not be in the database.
    3. Managed state: Also known as free state or offline state, it means that persistent state objects have lost their association with sessions, and managed state objects have OIDs, which may or may not
    exist in the database. For managed objects, hibernet cannot detect when it changes.
Seven, Hibernate annotation development
    1.PO class annotation development
        @Entity declare an entity
        @Table to describe the class and table corresponding
        @Id to declare a primary key
        @GenerateValue use it to declare a primary key generation strategy
        is equivalent to native by default, you can choose Primary key generation strategy AUTO IDENTITY SEQUENCE
        @Column to define columns
      Note: For all attributes in PO class, if you do not write annotations, the corresponding columns will also be generated in the table by default. The name of the column is the name of the attribute
        @Temporal to declare the date type
          TemporalType.DATA only has the year, month and day
          . TemporalType.TIME has only the hour, minute and second.
          TemporalType.TIMESTAMP has the year, month, day, hour, minute and second
    . 2. One-to-many (many-to-one)      
        @OneToMany
        @ ManyToOne
    3. Cascade
        @Cascade
8. Overview of Hibernate retrieval methods
    Hibernate provides the following 5 retrieval methods:
        1 Navigation object graph retrieval method, navigate to other objects according to the loaded objects
        2.OID retrieval method, according to the object's OID to retrieve objects
        3.HQL retrieval method, using object-oriented HQL query language
        4.QBC retrieval method, using QBC (Query by Criteria) API to retrieve objects, this API encapsulation is based on character The query statement in the form of a string provides a more object-oriented query interface
        5. Local SQL retrieval mode, using the SQL query statement of the local database
9. Hibernate
    transaction
        management

<property name="hibernate.connection.isolation">4</property>

        1 represents the transaction isolation level of READ UNCOMMITTED
        2 represents the transaction isolation level of READ COMMITTED
        4 represents the transaction isolation level of REPEATABLE READ
        8 represents the transaction isolation level of SERIALIZABLE
        EAD_UNCOMMITED read uncommitted, it causes all isolation problems
        READ_COMMITTED read has Commit, prevent dirty reads, non-repeatable reads and virtual reads may occur.
        REPEATABLE_READ Repeated reads prevent dirty reads, non-repeatable reads may occur virtual reads
        SERIALIZABLE Serialization solves all problems. Two transactions are not allowed to operate on a target data at the same time. (Inefficiency)
        ORACLE defaults to transaction isolation level READ_COMMITTED
        MYSQL default transaction isolation level REPEATABLE_READ
    2. Session management in
        Hibernate Hibernate provides three ways to manage sessions:
          (1) The life cycle of the Session object is bound to the local thread (ThreadLocal )
          (2) The life cycle of the Session object is bound to the JTA transaction (distributed transaction management)
          (3) The Hibernate delegate program to manage the life cycle of the Session

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324905457&siteId=291194637