Hibernate introduction, hibernate

Source: Internet
Author: User

Hibernate introduction, hibernate

 

1. What is Hibernate?

Hibernate is an open-source object relationship ing framework that encapsulates JDBC objects in a lightweight manner, so that Java programmers can use the object programming thinking to manipulate the database as they wish.

Programmers often only need to define the poing relationship between POJO and database tables to complete the persistent layer operations through the methods provided by Hibernate. Programmers do not even need to be familiar with SQL. Hibernate/OJB will automatically generate the corresponding SQL based on the developed storage logic and call the JDBC interface for execution.

2. What is the role of Hibernate?

Hibernate can directly access objects. Hibernate automatically converts the access to SQL to achieve indirect access to the database, thus simplifying code development at the data access layer.

3. Why Hibernate?

Compared, you will know why Hibernate has many benefits. Currently, jdbc and Mybatis are popular database operations. Here, we are not comparing other frameworks, but here we have highlighted this Hibernate framework.

 

1. it encapsulates jdbc and simplifies a lot of repetitive code. 2. simplified the coding of the DAO layer and made development more object-oriented. 3. Good portability and support for various databases. If you change a database, you only need to change the configuration in the configuration file. You do not need to change the hibernate code. 4. Transparent persistence is supported because hibernate operates purely (pojo) java classes without implementing any interfaces and is not invasive. Therefore, it is a lightweight framework.

 

(1) Comparison with jdbc.

(2) compare with Mybatis.

Other comparisons:

1. hibernate is fully automated, while mybatis is semi-automated. Hibernate can use the object relational model to perform database operations. It has a complete JavaBean object and database ing structure to automatically generate SQL statements. However, mybatis only supports basic field ing, and the actual relationship between object data and objects still needs to be implemented and managed through handwritten SQL. 2. hibernate databases are much more portable than mybatis databases. Hibernate uses its powerful ing structure and hql language to greatly reduce the coupling between objects and databases (oracle, mysql, and so on), while mybatis needs to write SQL, therefore, the coupling with the database directly depends on the programmer's method of writing SQL. If SQL is not universal and uses many SQL statements of a certain database, the portability will be much lower and the cost will be high. 3. hibernate has a complete log system, while mybatis lacks. The hibernate log system is sound and widely used, including SQL record, link exception, optimization warning, cache prompt, and dirty data warning. In addition to the basic record function, mybatis, features are much weaker.

 

4. How Hibernate works

 

(1) read and parse the hibernate. cfg. xml Configuration file through Configuration (). configure. (2) The parsing ing information is read by <mappingresource = "com/xx/User. hbm. xml"/> In hibernate. cfg. xml. (3) Use config. buildSessionFactory (); // to get sessionFactory. (4) sessionFactory. openSession (); // get the session. (5) session. beginTransaction (); // start the transaction. (6) persistent operate; (7) session. getTransaction (). commit (); // commit transaction (8) Close session; (9) Close sessionFactory; 5. Core Hibernate classesHibernate has six core classes and interfaces: Session, SessionFactory, Transaction, Query, Criteria, and Configuration. These six core classes and interfaces are used in any development. Through these interfaces, you can not only access persistent objects, but also control transactions. The Session interface is responsible for executing the CRUD operation on the Persistent Object (the CRUD task is to complete the communication with the database, including many common SQL statements ). However, it should be noted that the Session object is non-thread-safe. At the same time, the Hibernate session is different from the HttpSession In the JSP application. Here, when session is used, it actually refers to the session in Hibernate, and later the HttpSession object will be called the user session. SessionFactory interface initializes Hibernate. It acts as a proxy for the data storage source and is responsible for creating Session objects. The factory model is used here. Note that SessionFactory is not lightweight, because generally, only one SessionFactory is required for a project. When you need to operate multiple databases, you can specify a SessionFactory for each database. Transaction

The Transaction interface is an optional API. You can choose not to use this interface. Instead, it is replaced by the underlying Transaction processing code written by the Hibernate designer. The Transaction interface is an abstraction of the actual Transaction implementation. These implementations include JDBC transactions, UserTransaction in JTA, and even CORBA transactions. This design allows developers to use a unified transaction operation interface so that their projects can be easily transplanted between different environments and containers.

The Query interface allows you to easily Query databases and persistent objects. It can be expressed in HQL or SQL statements of local databases. Query is often used to bind Query parameters, limit the number of Query records, and finally perform Query operations. The Criteria interface is very similar to the Query interface, allowing you to create and execute object-oriented standardized queries. It is worth noting that the Criteria interface is also lightweight and cannot be used outside the Session. The Configuration class configures and starts Hibernate. During Hibernate startup, the Configuration instance first locates the ing document, reads the configurations, and creates a SessionFactory object. Although the Configuration class only plays a small role in the entire Hibernate project, it is the first object encountered when hibernate is started.

 

6. Configure the Hibernate primary key generation

 

The AssignedAssigned mode is used to generate the primary key value by the user, and must be specified before save (). Otherwise, an exception is thrown. The value generated for the primary key is determined by the user and is irrelevant to the underlying database. You need to maintain the primary key value. You must specify the primary key value before calling session. save. HiloHilo uses the high/low bit algorithm to generate a primary key. The high/low bit algorithm uses a high value and a low value, and then Concatenates the two values obtained by the algorithm as the unique primary key in the database. The Hilo method requires additional database tables and fields to provide the high value source. By default, the table used is hibernate_unique_key, and the default field is next_hi. Next_hi must have a record or an error may occur. Features: Additional database tables are required to ensure the uniqueness of primary keys in the same database, but they cannot guarantee the uniqueness of primary keys between multiple databases. The Hilo primary key generation mode is maintained by Hibernate. Therefore, the Hilo mode has nothing to do with the underlying database. However, you should not manually modify the values of the tables used by the hi/lo algorithm. Otherwise, duplicate primary keys may occur. The IncrementIncrement method automatically increases the primary key value to generate a new primary key value. However, the primary key type of the underlying database must be long, int, and other numeric types. The primary key increments in numerical order, and the increment is 1. /* Features: it is maintained by Hibernate and applicable to all databases. It is not suitable for multi-process concurrent database updates and is suitable for accessing databases by a single process. Cannot be used in a cluster environment. */The IdentityIdentity method supports automatic growth based on the underlying database. Different databases use different primary key growth methods. Features: it is related to the underlying database and requires that the database support Identity, for example, auto_increment in MySQl and Identity in SQL Server. Supported databases include MySql, SQL Server, DB2, Sybase, and HypersonicSQL. Identity does not require Hibernate and user interference. It is easy to use, but it is not convenient to transplant programs between different databases. SequenceSequence requires the support of the underlying database in the Sequence mode. For example, the features of the Oracle database: the support of the underlying database is required, database supporting sequences include DB2, PostgreSql, Oracle, SAPDb, and other Porting Programs between different databases. In particular, You need to modify the configuration file from a database supporting sequences to a database that does not support sequences. NativeNative primary key generation method automatically selects the Identity, Sequence, and Hilo primary key generation method based on different underlying databases. Features: different underlying databases use different primary key generation methods. Hibernate uses different ing methods based on the underlying database, so it is easy to port the program. This method can be used if multiple databases are used in the project. UUIDUUID uses the 128-bit UUID algorithm to generate a primary key. This ensures the uniqueness of the primary key in the network environment and the uniqueness of the primary key in different databases and different servers. Features: it can ensure the uniqueness of primary keys in the database. The generated primary keys occupy a large amount of storage space Foreign GUIDForeign for one-to-one relational systems. The GUID primary key generation method uses a special algorithm to ensure the uniqueness of the generated primary key. It supports SQL Server and MySQL

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.