Hibernate How it works and why it works ?

Read and parse the configuration file

Read and parse the mapping information , establish SessionFactory

open Sesssion

Create transaction Transation

Persistent operation

Commit transaction

close Session

close SesstionFactory

use Hibernate The framework does not need us to write a lot of tedious SQL sentence .Hibernate Realized ORM, Ability to map objects to database tables , So as to simplify our development !

 

Hibernate How to delay loading ( Lazy loading )?

By setting properties lazy Set whether lazy loading is required

When Hibernate When querying data , The data does not exist in memory , When the program actually operates on the data , Object exists in memory , Delay loading is realized , It saves memory on the server , This improves the performance of the server .

 

Hibernate How to realize the relationship between classes in ?( as : One to many , Many to many relationship )

They are generated through the many-to-one,one-to-many,many-to-many To realize the association between classes .

 

hibernate How to change between the three states of

Hibernate The state of the object in :

temporary / Instantaneous state

Persistent state

Free state

 

temporary / Instantaneous state

When we directly new The object is temporary / Transient state ..

 

The object has not been persisted 【 Not saved in the database 】

Not subject to Session The management of

Persistent state

When an object is stored in a database, it is persistent

 

When calling session Of save/saveOrUpdate/get/load/list When we wait for the method , Objects are persistent states

There is corresponding data in the database

suffer Session The management of

When you make changes to the properties of an object , Will be reflected in the database !

Free state

When Session After closing , Persistent objects become free ...

Not in session The management of

There are corresponding records in the database

 

compare hibernate The advantages and disadvantages of the three retrieval strategies

Search now :

advantage : Completely transparent to applications , Regardless of whether the object is persistent , Or free , It's easy to navigate from an object to its association with an application ;

shortcoming : 1.select Too many statements ;2. Many applications may not need to load memory to access objects in vain ;

Search now :lazy=false;

 

Delayed retrieval :

advantage : It's up to the application to decide which objects to load , Redundant executable can be avoided select sentence , And avoid loading objects that your application doesn't need to access . So it can improve the retrieval performance , And can save memory space ;

shortcoming : If the application wants to access the instance of the free state proxy class , It must be guaranteed that it has been initialized in the persistent state ;

Delayed loading :lazy=true;

Search for left outer connection :

advantage :
1 Completely transparent to applications , Regardless of whether the object is persistent , Or free , Applications can easily navigate from an object to its associated object .2 External connection is used ,select The number of statements is small ;

shortcoming : 1 Objects that the application does not need to access may be loaded , Waste a lot of memory space in vain ;2 Complex database table joins can also affect retrieval performance ;

Pre grab : fetch=“join”;

 

hibernate What cache policies are supported

usage The properties of are 4 species :

Objects placed in L2 cache , read-only (Read-only);

Non strict reading and writing (Nonstrict read/write)

Reading and writing ; Objects placed in the L2 cache can be read , write (Read/write);

Transaction based strategy (Transactional)

 

hibernate Inside sorted collection and ordered collection What's the difference?

sorted collection

It's in memory Java Comparator for sorting

ordered collection

It's in the database order by To sort

For larger data sets , To avoid sorting them in memory Java In OutOfMemoryError, Best use ordered collection

 

It's a deal. Hibernate The cache mechanism of virtual machine

L1 cache :

Hibenate Middle level cache , Also called session Cache for , It can be used in session Reduce the number of database accesses within the scope ! Only in session The scope is valid !
Session close , First level cache failure !

As long as the object state is persisted , All by Session Administration , in other words , All of them will be here Session In cache !

Session The cache for is created by hibernate maintain , Users cannot manipulate cached content ; If you want to manipulate the cache content , Must pass hibernate Provided evit/clear Method operation .

L2 cache :

The second level cache is based on the application cache , be-all Session Can be used

Hibernate The secondary cache provided has a default implementation , And it is a pluggable cache framework ! If users want to use L2 cache , All you need to do is hibernate.cfg.xml It can be configured in ;
I don't want to use it , Remove directly , Does not affect code .

If the user thinks hibernate The framework provided is not easy to use , You can change other cache frameworks or implement your own cache framework .

Hibernate L2 cache : It stores commonly used classes

 

Hibernate There are several ways to query

Object navigation query (objectcomposition)

HQL query

1, Property query

2, Parameter query , Named parameter query

3, Association query

4, Paging query

5, Statistical function

Criteria query

SQLQuery local SQL query

 

How to optimize Hibernate?

Ø Database design adjustment

Ø HQL optimization

Ø API The correct use of ( For example, select different sets and queries according to different business types API)

Ø Main configuration parameters ( journal , Query cache ,fetch_size, batch_size etc. )

Ø Map file optimization (ID Generation strategy , L2 cache , Delayed loading , Association optimization )

Ø Management of first level cache

Ø For L2 cache , There are also many unique strategies

 

chat Hibernate in inverse The role of

inverse Property default is false, That is to say, both ends of the relationship maintain the relationship .

such as Student and Teacher It's a many to many relationship , Use an intermediate table TeacherStudent maintain .Gp)

If Student here inverse=”true”,
So the relationship goes from one end to the other Teacher maintain , That is to say, when inserting Student Time , It doesn't work TeacherStudent surface ( Intermediate table ). only Teacher The operation on the intermediate table is triggered only when the table is inserted or deleted . So both sides inverse=”true” It's not right , Will cause any operation not to trigger the impact on the intermediate table ; When both sides inverse=”false” Or by default , Inserting a relationship twice in the middle causes the relationship to be inserted .

If the relationship between tables is “ One to many ” In my words , that inverse Only in “ One ” To configure !

 

JDBC hibernate and ibatis The difference between

jdbc: Manual

Write manually sql

delete,insert,update To get the value of an object one by one sql in , You cannot pass in an object directly .

select: What is returned is a resultset, To start with ResultSet Middle line , Take out one field by one , And then encapsulate it into an object , Does not return an object directly .

ibatis The characteristics of : Semi automation

sql Write it manually

delete,insert,update: Pass in an object directly

select: Returns an object directly

hibernate: fully automatic

No writing sql, Automatic packaging

delete,insert,update: Pass in an object directly

select: Returns an object directly

 

When the query speed is very slow in the database , How to optimize ?

Index

Reduce association between tables

optimization sql, Try to make sql Locate data quickly , Don't let me sql Make full table query , It should be indexed , Put the table with large amount of data at the front

Simplify query fields , Don't use useless fields , Control of the returned results has been established , Try to return a small amount of data

 

What is? SessionFactory, Is she thread safe

SessionFactory yes Hibrenate Singleton data storage and thread safety , So that it can be accessed by multiple threads at the same time . One SessionFactory
It can only be created once at startup .SessionFactory Various singletons should be packaged so that they can be easily stored in an application code .

 

get and load difference

1)get If not, it will return null, load If no exception is found, it will be thrown .

2)get The first level cache will be checked , Check the L2 cache again , Then check the database ;load The first level cache will be checked , If not found , Create a proxy object , Query the secondary cache and database when necessary .

 

merge The meaning of :

If session The same persistent identity exists in (identifier) Examples of , The old persistent instance is covered with the state of the object given by the user

If session There is no corresponding persistent instance , Then try to load from the database , Or create a new persistent instance , Finally, the persistent instance is returned

The object given by the user is not associated with session upper , It's still out of control

 

persist and save The difference between

persist Immediate enforcement is not guaranteed , It may have to wait flush;

persist Do not update cache ;

save, Persistent identifier of a transient instance , Timely generation , It returns the identifier , So it will execute immediately Sql insert

use save() Method to save persistent objects , This method returns the identity property value of the persistent object ( The primary key value of the corresponding record );

use persist() Method to save persistent objects , The method has no return value .

 

id generator What are the strategies

Automatic generation strategy of primary key

identity Self growth (mysql,db2)

sequence Self growth ( sequence ), oracle Self growth is realized by sequential method **

native Self growth 【 It will be selected according to the self growth mode of the underlying database identity or sequence】

If it is mysql database , What is the self growth mode identity

If it is oracle database , use sequence Self growth is realized by sequence

increment Self growth ( There will be concurrent access problems , Generally, there are problems when using in server cluster environment .)

Specify the primary key generation policy to manually specify the value of the primary key

assigned

Specifies that the primary key generation policy is UUID Generated value

 

Hibernate Naming in SQL What is a query ?

Named queries refer to queries that use <sql-query> The label is defined in the mapping document SQL query , You can use Session.getNamedQuery() Method to call it . Named queries enable you to get a specific query using a name you specify .

Hibernate Named queries in can be defined using annotations , You can also use the xml It's a question . stay Hibernate in ,@NameQuery Used to define a single named query ,@NameQueries Used to define multiple named queries .

 

sketch hibernate in getCurrentSession and openSession difference

1,getCurrentSession The current thread is bound , and openSession can't , Because we put hibernate Give it to us spring After I came to manage it , We have transaction configuration , This thread with transaction will bind each one in the current factory session, and openSession It's about creating a new one session.

2,getCurrentSession There is something wrong with business spring To control , and openSession We need to manually open and commit transactions ,

3,getCurrentSession We don't need to turn it off manually , Because the factory will manage itself , and openSession We need to turn it off manually .

4, and getCurrentSession We need to set the binding transaction mechanism manually , There are three settings ,jdbc Local Thread,JTA, The third one is spring Transaction management mechanism provided org.springframework.orm.hibernate4.SpringSessionContext, and srping This transaction management mechanism is used by default

 

Will it be ok Hibernate The entity class of is defined as final class ?

You can put Hibernate The entity class of is defined as final class , But it's not good . because Hibernate Proxy mode is used to improve performance in the case of delayed correlation , If you define an entity class as final After class , because
Java It's not allowed to final Class , therefore Hibernate You can no longer use the proxy , This limits the use of tools that can improve performance .

 

Technology