What is hibernate?
Hibernate in English is the meaning of hibernation, when winter comes, the world began to prepare for hibernation, but the program ape this animal does not seem to hibernate, because the demand has changed, to change the bug, hibernation, for the object is persistent. What is persistence? Persistence is the preservation of data (such as in-memory objects) in a permanently stored storage device, such as a disk, where the primary application of persistence is to store objects in memory in a database, or in a disk file, in an XML file, and so on. Persistence is the mechanism by which program data is transformed between a persistent state and a transient state. JDBC is a persistence mechanism, and file IO is a persistent mechanism.
There are many ways to persist in our lives, such as:
A, the fresh meat refrigerated, eat the time to thaw;
b, the fruit can be made;
C, the rapid freezing of human organs, transport, and then thawed to the need for transplant surgery. So, learning is all about life.
To get a deeper understanding of hibernate, we can help you understand hibernate in the following three ways:
A, from the angle of UBD
We know that the typical three-layer architecture is: U-layer, B-layer, D-layer, respectively, the presentation layer, the business layer, the persistence layer, hibernate is equivalent to the D layer we previously contacted, that is, the persistence layer framework, there are many persistence layer frameworks such as MyBatis, EJB and so on.
B, Hibernate is an open-source ORM Framework
ORM, Object-relational mapping, is a program technology that enables the conversion of data between different types of systems in an object-oriented programming language, and in effect, ORM creates a database of virtual objects that can be used in a programming language, simply speaking, Her role is to do a mapping between relational databases and objects, from object mapping to relationships, and from relationships to objects, so that when we manipulate databases, we don't need to deal with SQL anymore, as long as you manipulate the object like you do.
C, Hibernate is a further encapsulation of JDBC
Remember knocking at the computer room personal reconstruction, no use hibernate, there are a lot of redundant parts, a variety of JDBC statements, so in order to conform to the development of the times, we have JDBC packaging a bit, so that we can not manipulate the data, direct operation she is OK.
advantages and disadvantages of hibernate
Advantages:
A, more targeted
The use of the time only need to manipulate the object, is the development of more object, abandoned the central idea of the library, completely object-oriented thinking.
B, persistence
A single-threaded object with a persisted state with a business function that has a short lifetime. These objects may be ordinary Javabeans/pojo, and this object does not implement a third-party framework or interface, except that they are associated with (just one) session. Once this session is closed, the objects are left out of the persistence state, which can be used freely by any layer of the application. (for example, as a data transfer object that deals with the presentation layer.) )
C, there is no intrusion, that is, the so-called lightweight framework.
D, the transplant is very good.
E, caching mechanism, provide first-level cache and level two cache.
F, concise HQL programming.
G, submit productivity.
Disadvantages:
A, using the database characteristics of the statement, it will be difficult to tune
b, there are problems in large-scale data update
C, there are a lot of attack query function in the system
D, not suitable for bulk operations, which is also a weakness of the or framework, to use the database of the specific optimization mechanism, not suitable for hibernate.E, the efficiency is slightly worse than JDBC
Hibernate and MyBatis
The same point: Hibernate and MyBatis can be generated sessionfactory by Sessionfactorybuider from an XML configuration file and then generated by the sessionfactory session, Finally, the session is opened to execute the transaction and SQL statements. The life cycle of the sessionfactorybuider,sessionfactory,session is similar.
Different points:
MyBatis: Small, convenient, efficient, simple, direct, semi-automatic
Hibernate: Powerful, convenient, efficient, complex, mealy, fully automatic
MyBatis
A, easy to get started, that is, learn to use, provide automatic object binding function of database query, and continue a very good experience of SQL use, for not so high object model requirements of the project, quite perfect.
b, you can do more detailed SQL optimization, you can reduce the query field.
C, the disadvantage is that the framework is still relatively humble, the function is still missing, although the data binding code is simplified, but the entire underlying database query is actually to write their own, the workload is relatively large, and it is not easy to adapt to rapid database modification.
D, level Two cache mechanism is poor.
Hibernate:
A, powerful, database-independent, O/R mapping ability, if you are quite proficient in hibernate, and hibernate is properly encapsulated, then your project the entire persistence layer code will be quite simple, need to write the code is very small, rapid development, very cool.
b, there is a better level two caching mechanism, you can use a third-party cache.
C, the disadvantage is that the learning threshold is not low, to master the threshold is higher, and how to design O/R mapping, how to balance the performance and the object model, and how to use good hibernate needs your experience and ability are very strong.
To give an image of the metaphor:
MyBatis: Mechanical tools, easy to use, take to use, but work or to do their own, but the tool is alive, how to make up my mind.
Hibernate: Intelligent robot, but the cost of research and development (learning, proficiency) is very high, work can get rid of him, but limited to what it can do.
Hibernate development and Environment building
The first part of the small section of the main simple introduction of hibernate related theoretical knowledge, Next, the theory of contact practice, small series to do a simple demo, hope to help small partners better grasp hibernate, shortcomings, but also please small partners to advise.
A, hibernate environment to build so easy, a variety of introduction jar package, the relevant jar file has been uploaded, click to download, without integral, not too grateful, small series of the name of Lei Feng, hibernate core Package, Hibernate dependency package.
b, join the database driver, the following demo database using Mysql,so need to introduce MySQL driver, click to download.
C, provide the core configuration file Hibernate.cfg.xml file (in the SRC folder), where the configuration is as follows (for MySQL), the small partners can check their own other databases how to configure. OK below to start Demo:
The first step, write the Hibernate.cfg.xml file, complete the basic configuration, the code is as follows:
<! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">
The second step, establishing the entity class User.java code is as follows:
Package Com.bjpowernode.hibernate;import Java.util.date;public class User {private string id;private string name; private string password;private date createtime;private date expiretime;public String getId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public Date Getcreatetime () {return createtime;} public void Setcreatetime (Date createtime) {this.createtime = Createtime;} Public Date Getexpiretime () {return expiretime;} public void Setexpiretime (Date expiretime) {this.expiretime = Expiretime;}}
The third step, write the User.hbm.xml file, complete the Entity class mapping, the specific code is as follows:
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
Fourth Step, add the User.hbm.xml file to the Hibernate.cfg.xml file, as shown in the following code:
<! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">
The fifth step, write the tool class Exoprtdb.java, will HBM generate DDL, that is, HBM2DDL, the code is as follows:
Package Com.bjpowernode.hibernate;import Org.hibernate.cfg.configuration;import org.hibernate.tool.hbm2ddl.schemaexport;/** * Generate DDL for HBM * @author Administrator * */public class Exportdb {public static V OID Main (string[] args) {//default read hibernate.cfg.xml file configuration cfg = new configuration (). Configure (); Schemaexport export = new Schemaexport (CFG); Export.create (true, True);}}
The sixth step is to build the client class clients, add user data to MYSLQ, and the code looks like this:
package Com.bjpowernode.hibernate;import Java.util.date;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;public class Client {public static void main ( String[] (args) {//Read Hibernate.cfg.xml file configuration cfg = new configuration (). Configure ();// Establish Sessionfactorysessionfactory factory = Cfg.buildsessionfactory ();//Get sessionsession session = Null;try{session = Factory.opensession ();//Open things session.begintransaction (); User user = new user (), User.setname ("Zhang San"), User.setpassword ("123"); User.setcreatetime (new Date ()); user.setexpiretime (New Date ());//Save User Object Session.save (user);//Commit thing session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace ();//Rollback thing session.gettransaction (). rollback (); Finally{if (Session! = NULL) {if (Session.isopen ()) {///close Sessionsession.close ();}}}}
Finally, let's take a look at the effect as follows:
Small Editor's note: This blog small part of the main simple introduction of hibernate related knowledge, introduced what is Hibernate, hibernate advantages and disadvantages, hibernate and MyBatis objects, and finally a simple introduction of a demo , through the demo above we can see that in the code does not involve any JDBC code, as a developer only need to write the corresponding entity class, and then through the configuration can implement the table and the table to implement data insertion. In the code there are many of Hibernate's core objects, such as configuration, sessionfactory, session, etc., with the depth of learning, the content of these small parts will be one by one related to the introduction, SSH tour, not to be continued ...
"SSH series"--Hibernate fundamentals && Getting Started Demo