7-point collation and summary of Hibernate's underlying principles

Source: Internet
Author: User

Have a nice smile

"Wife wants to lose weight, let her husband help her buy diet pills, husband: Medicine health, now very good, more sensual ah." Son: Actually really a bit fat, the husband immediately stared at the son one eye: children don't know not to say, your mother this stature I like. Then, while the wife did not pay attention to the hard lesson of the son: after the attention point, weight loss medicine is very expensive, you want to tell your mother, eat less food not to reduce. It's all a routine ... "

Ask questions

For Hibernate, a personal 7-point simple collation and summary???

solve the problem 1.Hibernate Brief Introduction

Hibernate is an open source object-relational mapping framework that provides JDBC with a very lightweight object encapsulation that maps Pojo to database tables, is a fully automated ORM framework, and Hibernate automatically generates SQL statements, automatically executes, So that Java programmers can use object programming thinking to manipulate the database at will.

advantages and disadvantages of 2.Hibernate 2.1 Advantages
    • The program is more object-oriented;
    • Increased productivity;
    • Easy porting (Modify configuration file);
    • No intrusion.
2.2 Disadvantages
    • The efficiency is slightly worse than JDBC;
    • Not suitable for bulk operations.
    • Only one association relationship can be configured
2.3 Non-invasive

Simple to understand, so-called intrusive, is that it does not invade any of Hibernate's APIs. Instead of inheriting one of Hibernate's base classes or implementing an interface to hibernate, use plain Java objects (POJO) entirely.

For example: A is intrusive and a is used in B code, so if you do not use a later (instead of another tool), you must modify the code of B. Conversely, if a is non-invasive, B does not use a, C, code does not need to change, change the configuration file or something, you can.

3.Hibernate has four kinds of query scheme 3.1 Query by ID

Depending on the Get,load method, the object is found based on the ID.

For example:

load(Class theClass, Serializable id) load(Class theClass, Serializable id, LockMode lockMode)load(Object object, Serializable id)  
3.2 HQL statement to query

HQL (Hibernate query Language), querying object: Query. Query is generated by the CreateQuery () in the session.

For example:

 //不带参数的查询(这类比较简单) Query query=session.createQuery("select user from User as user"); //第一种带参数的查询 Query query=session.createQuery("select user from User as user where user.name=?"); //假设name为传过来的参数 query.setString(0,name) //第二种带参数的查询 Query query=session.createQuery("select user from User as user where user.name=:name"); query.setString("name",name)//假设name为传过来的参数(多个参数以此类推)  利用Session接口的find查询,均返回list find(String query) find(String query, Object[] values, Type[] types) find(String query, Object value, Type type)      //例如下面List list=session.find("select user from Users as user where user.name=?",name,Hibernate.STRING)List list=session.find("select user from Users as user where user.name=? and             user.pw=?",new Object[]{name,pw},new Type[]{Hibernate.STRING,Hibernate.STRING})
3.3 Criteria Query

Criteria (standard query language), query object: Criteria, query criteria: Criterion.

The specific example is as follows: Omit User class

  @Test public void Test () {//Get the criteria instance object criteria = Session.createcriteria (User.class); Check out the employee of Wang surname and income between 3000 and 5000///similar to HQL where EmployeeName like ' Wang ' and salary between and the List E MPs = Criteria.add (Restrictions.like ("EmployeeName", "Wang%")). Add (Restrictions.between ("salary", 3000.0, 5000.      0). List (); Employees with a salary of less than 4000 or 5000 or more can be logically grouped by restrictions or OR and Emps = Criteria.add (Restrictions.like ("EmployeeName      "," Wang% ")). Add (Restrictions.or (restrictions.gt (" salary ", 5000D), restrictions.lt (" salary ", 3000D)). List (); Check out the position is a software engineer or a test engineer, and the degree is a master, undergraduate or tertiary staff what Emps = Criteria.add (restrictions.in ("position", new string[] {"Software engineer", "Test Engineer"}). Add (Restrictions.disjunction (). Add (Restrictions.eq ("degree", "Master")). Add (Restrictions.eq ("degree"  , "undergraduate")). Add (Restrictions.eq ("degree", "College")). List (); }  

For more details, see the Great God article on the web below, which does not continue to expand.

3.4 Using SQL to check

Query object: sqlquery

Session.createSQLQuery();

The most basic SQL query is to get a list of scalar (numeric)

Session.createSQLQuery("SELECT * FROM CATS").list();Session.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").list();

Here's how to get a native query to return an entity object with Addentity ().

Session.createSQLQuery("SELECT * FROM CATS").addEntity(Cat.class);Session.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").addEntity(Cat.class);

For more details, see the Great God article on the web below, which does not continue to expand.

How the 4.Hibernate works and initializes 4.1 Working principle
    • After configuring Hibernate's configuration file and the configuration file corresponding to the class, start the server
    • The server instantiates the configuration object, reads the contents of the Hibernate.cfg.xml file, and builds the table or establishes a mapping relationship with the table according to related requirements.
    • The Sessionfactory instance can be established by instantiating the configuration object, and further, the session object can be created through the Sessionfactory instance.
    • After the session, the database can be added to check the operation, in addition to more complex full-text search, simple operation can be done through the Hibernate package session built-in method to achieve
    • In addition, it is possible to implement more complex database design through the association of Things management and tables.
      Advantage: Hibernate corresponds to the bridge between Java class and database table, we can do a lot of things through this bridge.
4.2 Initialization

1. Through configuration config = new configuration (). Configure ();//Read and parse the Hibernate.cfg.xml config file
2. Read and parse the mapping information from the Hibernate.cfg.xml
3. Via sessionfactory SF = Config.buildsessionfactory ();//Create Sessionfactory
4.Session Session = Sf.opensession ();//Open Sesssion
5.Transaction tx = Session.begintransaction ();//Create and start transaction transation
6.persistent operate operation data, persistent operation
7.tx.commit ();//Commit a transaction
8. Close session
9. Close Sesstionfactory

3 kinds of object states for 5.Hibernate 5.1 Temporary state (or transient state transient)

A Java object that opens up memory space by the new command, for example:

User user=new User();

Temporary objects exist in memory isolation, which is the carrier that carries information, and does not have any correlation with the database data.

5.2 Persistent State (persistent)

The object in this state has a corresponding record in the database and has a persistent identity. Objects obtained through the session's get (), load () are persistent objects. After the persisted object is modified, it is not synchronized to the database immediately until the database transaction commits. Persistent objects are dirty until they are synchronized.

5.3 Free State (or detached state)

When the session associated with a persistent object is closed, the persisted object is turned into a free object. When the free object is re-associated to the session, it is again transformed into a persistent object (changes in detached will be persisted to the database). A free object has a recognized value for the database, but it is not within the scope of persistent management.

6.Hibernate Object state Transitions 6.1 Converting pictures

6.2 Description of object state transitions

temporary State or transient state (transient)
-not in the session cache, there is in memory
-There are no object records in the database

How Java enters a temporary state
-When you just created an object with the new statement
-When the Delete () method of the session is called, when an object is deleted from the session cache.

persistent State (persisted)
-In the session cache.
-Object records are persisted in the object database.
-The Session will be synchronized at a specific time.

How Java enters the persistence state
-Session Save () persists the temporary->>> status.
-The Session's load (), the Get () method returns the object.
-The Session's find () returns the object that is stored in the list collection.
-Session update (), Saveorupdate () to make free->>> persistent.

Free State or managed state (detached)
-It is no longer in the Session cache.
-The free object is transformed from a persistent state, and there may be a corresponding record in the database.

How Java enters the persistent state->>> Free State
-The Close () method of the Session
-The Session's evict () method, which removes an object from the cache, improves performance and is less used.

7.Hibernate Cache 7.1 Why caching is required

Hibernate is a persistent layer framework that accesses physical databases frequently. Improve application performance by reducing the frequency of application access to physical data sources. The data in the cache is a copy of the data in the physical data source, the application reads and writes data from the cache at run time, and at a particular moment or event synchronizes the cache and the data from the physical data source.

7.2 Hibernate Cache Classification

Hibernate cache is also known as Session caching:

    • Session built-in cannot be uninstalled
    • Session cache is a transaction-scoped cache
    • The life cycle of a session object typically corresponds to a database transaction or an application transaction

The hibernate level two cache is also known as the Sessionfactory cache:

The second-level cache is optional and is a configurable plug-in, which is not enabled by default under Sessionfactory.

7.2 Hibernate cache query mechanism
    • When hibernate accesses data objects based on their IDs, the first cache is checked from the session level.
    • Not found, if a level two cache is configured, then from the level two cache;
    • If it is not found, then query the database, put the results in the cache by ID
    • Update the cache while deleting, updating, and adding data.
Reading Comprehension

From Murakami's "the Seaside Kafka"

    • You are no longer the one who escaped from the sandstorm.
    • "I want you to remember me," Saeki said, "It doesn't matter if you remember me, and everyone else forgets." ”
    • Things that cannot be accurately expressed in words are best not to be said at all.
    • People are not because of their shortcomings, but because of their merits are dragged into a larger tragedy.
    • There must be order in things, too advanced to see. Look too ahead, bound to ignore the foot, people tend to fall. But on the other hand, the light looks at the foot also not. Don't look ahead, what will hit. So, how much to look forward at the same time to deal with the immediate things. This is the key, no matter what you do.
    • We all continue to lose all kinds of precious things, precious opportunities and possibilities, irreparable affection, which is a meaning of survival.
    • If you have a surprising great idea is that you alone, then in the deep darkness of the wandering is also must be you alone.
    • To ask is a moment's shame, not to ask is the shame of life.
Classic Story

"A hotel is very well managed, popular and prosperous. The boss of the hotel is ready to do another business, because there is not much energy to manage the hotel, it intends to find a general manager in the existing three department managers.
Mister asked the first department manager: "Is there a chicken or an egg first?" ”
The first department manager, in a word, answered, "There are chickens first." ”
Mister then asked the second department manager: "Is there a chicken or an egg first?" ”
The second department manager answered confidently, "There are eggs first." ”
At this point, Mister to the last department manager said: "You say, is the first chicken or eggs?" ”
The third department manager earnestly replied: "The customer First order the chicken, first has the chicken, the guest first order the egg, first has the egg." ”
Mister laughed. He decided to move the Third department manager to the general manager of the hotel.
"Heart language" is often easily confined to a small circle, which is often said: inertia thinking. When you can't jump out, you can't find the right way to get things done; on the contrary, when we jump out of the original inertial thinking of the box, we embarked on a new road, namely: steady another spring. 】

Great God article

"1" Hibernate Baidu Encyclopedia
"2" Hibernate interview Knowledge points summary
"3" Hibernate query Solution
"4" Hibernate criteria Query
"5" Hibernate native SQL query
"6" Hibernate sqlquery native SQL query and return result set processing-1
"7" Hibernate working principle and function
The Hibernate4.3 of "8" hibernate, a new formulation of the initialization of the initial process
Three states of the "9" (GO) Hibernate object
Three States of objects in "10" hibernate and their mutual transformation
"11" Hibernate caching mechanism

other

If there is a little bit of happiness for you, let happiness continue to pass, welcome to praise, top, welcome to leave valuable comments, thank you for your support!

7-point collation and summary of Hibernate's underlying principles

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.