Hibernate core classes and interfaces detailed description

Source: Internet
Author: User


First, Hiobernate core class and Interface preview diagram


Second, hibernate.properties

This file is similar to the Hibernate.cfg.xml file used in previous versions, and the effect is consistent with hibernate.cfg.xml.

Three, Hibernate.cfg.xml (1) Detailed introduction

① This file is used primarily to specify individual parameters, is the hibernate core file
The ② is placed in the SRC directory by default, or it can be placed under a different directory.
③ Specifies the driver, user name, password, URL, connection pool of the connection database.
④ Specifies the location of the object-relational mapping file.
⑤ can also use the Hibernate.properties file to replace the file. (Recommended for use with Hibernate.cfg.xml).

(2) configuration file template
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hibern Ate.sourceforge.net/hibernate-configuration-3.0.dtd "><!--Hibernate core configuration file-->< hibernate-configuration><session-factory><!--configuration uses driver--><property name= "Connection.driver_ Class ">com.mysql.jdbc.driver</property><property name=" Connection.username ">root</property ><property name= "Connection.password" >xu827928</property><property name= "Connection.url" > jdbc:mysql://127.0.0.1:3306/hbmtest</property><!--Configure the dialect dialect to explicitly tell hibernate which database is connected-->< Property name= "dialect" >org.hibernate.dialect.MySQLDialect</property><!--shows the corresponding SQL statement-->< Property Name= "Show_sql" >true</property><!--formatted output SQL statement--><property name= "Format_sql" >true </property><!--let hibernate create a table for US--><!--update: Create a table if there are no tables if you see a tableWhether the structure changes if there is a change creates a new table if not, add create: Create a new database every time--><!--<property name= "Hbm2ddl.auto" >create</property >--><property name= "hbm2ddl.auto" >update</property><!--Specify the Management object mapping file--><mapping resource = "Com/lc/domain/employee.hbm.xml" ></mapping></session-factory>

Iv. *.hbm.xml

(1) Object Relational mapping file (*.hbm.xml)① The main role of this file is to establish the mapping of tables and classes, which is an indispensable and important document.
② are generally placed in the same directory as their mappings, but are not required.
③ naming is typically the class name. Hbm.xml, but not required.

④:


(2) configuration file template
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping Public '-//hibernate/hibernate mapping DTD 3.0//en ' Http://hibernate.sourceforge. Net/hibernate-mapping-3.0.dtd ' ><!--This is the hibernate-->< that maps the employee table!--the file is used to configure the mapping relationship for domain objects and tables-->< Hibernate-mapping package= "Com.lc.domain" ><class name= "employee" table= "employee" ><!--ID element for specifying PRIMARY key properties-- ><id name= "id" column= "id" type= "java.lang.Integer" ><generator class= "increment"/> </id><!- -Configuration of other properties--><property name= "name" type= "java.lang.String" ><column name= "name" not-null= "false"/> </property><property name= "Email" type= "java.lang.String" ><column name= "email" not-null= "false"/ ></property><property name= "HireDate" type= "java.util.Date" ><column name= "HireDate" not-null= " False "/></property></class>
Configuration Class (1) Detailed introduction

① is responsible for managing hibernate configuration information.
② Read Hibernate.cfg.xml
③ loads the driver, url, user name, password, connection pool configured in the Hibernate.cfg.xml configuration file.
④ manages *.hbm.xml object relational files.

(2) Schematic code:Configuration Cf=new configuration (). Configure ();

Vi. Sessionfactory (Session Factory) interface (1) detailed description

① caching SQL statements and some data

② is created at the time of application initialization, is a heavyweight class (eats memory), and generally uses a singleton pattern to ensure that only one sessionfactory instance is needed in an application.

③ If an app accesses multiple databases, it creates multiple session factory instances, typically a single session factory instance of a database.
④ can obtain a session instance through the Sessionfactory interface.

(2) Schematic code:
Configuration Cf=new configuration (). Configure ();  Sessionfactory sf=cf.buildsessionfactory ();  Session s=sf.getcurrentsession ();  Or: Session s=sf.opensession ();

Vii. Session Interface (1) interface Introduction

①session An instance represents a single operation with the database (of course, one operation can be a crud combination)

②session instances are obtained through sessionfactory and need to be closed.
③session is a thread that is not synchronized (unsafe), so to be sure to use it in the same thread, you can use Getcurrentsessiong ().
④session can be seen as a persistence manager, which is an interface associated with persistent operations

(2) Schematic code:
Configuration Cf=new configuration (). Configure (); Sessionfactory sf=cf.buildsessionfactory (); Session s=sf.getcurrentsession ();//or: Session s=sf.opensession ();
(3) Several important methods of Session interface

The session is generally manipulated as an object, where
Give us a demonstration! (Please refer to the documentation)
① saving an object (record)-save method
② Delete an object (record)-delete method
③ querying an object (record)-get/load method
④ modifying an object (record)-update method

(4) difference between get () and load ()

1, the Get () method returns the entity class directly, and returns NULL if no data is found. Load () will
Returns an entity proxy object (currently this object can be automatically converted to an entity object),
But when the proxy object is called, if no data is present, it throws a
Org.hibernate.ObjectNotFoundException exception
2.load first to cache (session cache/Level two cache) to check, if not, return a
Proxy object (not to be found in db immediately), and so on later when using this proxy object operation
To the DB, which is what we often say load is supported by default in the case of delay plus
Load (lazy)
3. Get first to cache (session cache/Level two cache), if not, go to DB
(i.e. issue SQL immediately). Anyway, if you're sure there's this object in the DB,
Load (), not sure to use get () (so high efficiency)

(5) difference between opensession () and Getcurrentsession ()

The session created by ① with Getcurrentsession () is bound to the current thread, while the session created with Opensession () will not

The session created by ② with Getcurrentsession () is automatically closed at commit or rollback, and the session created with Opensession () must be closed manually.
③ using getcurrentsession () needs to include in the Hibernate.cfg.xml file

The following configuration:
* If you are using a local transaction (JDBC Transaction)
<property name= "Hibernate.current_session_context_class" >thread</property>
* If you are using a global transaction (JTA Transaction)
<property name= "Hibernate.current_session_context_class" >jta</property>
Simply explain the differences between JDBC and JTA transactions.

(6) Contact opensession () and Getcurrentsession ()

In-depth discussion:
When the sessionfactory is started, Hibernate will create the corresponding Currentsessioncontext according to the configuration, and when the Getcurrentsession () is called, the actual method to be executed is Currentsessioncontext.currentsession ().

When Currentsession () executes, currentsession calls Sessionfactory Opensession if the current session is empty.

(7) Who do Opensession () and getcurrentsession () choose?

Principle:
① If you need to use the same session in the same thread, use Getcurrentsession ()
② If you need to use a different session in a thread, use Opentsession ()

(8) Opensession () and getcurrentsession (), using threadlocal mode (thread local variable mode) to manage the session, the code is as follows:

public class Hibernateutil {public static final ThreadLocal session =new ThreadLocal ();p ublic static final sessionfactory Sessionfactory;   static {      try {        sessionfactory = new Configuration (). Configure (). Buildsessionfactory ();      } catch (Throwable Ex) {           throw new Exceptionininitializererror (ex);      }     }  public static session Currentsession () throws Hibernateexception {        session s = Session.get ();        if (s = = null) {          s = sessionfactory.opensession (); Session.set (s);}         return s;}     public static void CloseSession () throws Hibernateexception {           Session s = session.get ();        if (s! = null) {S.close ();}        Session.set (NULL); }}

Viii. Transaction (Transaction) interface(1) Here we simply show you what a business is.

A transaction is simply a set of operations on a database that either succeeds or fails altogether. This ensures consistency of data and atomicity of transactions.
①transaction is an abstraction of the underlying object implementation.
② may be a JDBC or JTA transaction, which facilitates hibernate migration in different execution environments.
③hibernate requires that the calling transaction be displayed (if only the query can not be called.)

Transaction ts=s.begintransaction ();
...
Ts.commit (); S.close (); Ts.rollback () rollback is required for an exception to occur.

Nine, query interface

(1) The object of the query interface type can operate on the database, and it can use HQL,QBC,QBE and native SQL (native SQL) to operate on the database. The official recommendation is to use the HQL statement.

Ten, the Criteria interface

The criteria interface can also be used for object-oriented queries, and for its specific usage we
Here is not a brief introduction, a few examples.
The simplest case: return 50 records

Criteria crit = Sess.createcriteria (Cat.class); Crit.setmaxresults (50); List cats = Crit.list ();
Restricting the contents of a result set
List cats = Sess.createcriteria (Cat.class)  . Add (Restrictions.like ("name", "fritz%")  . Add ( Restrictions.between ("Weight", Minweight, Maxweight))  . List ();


NOTE: Reprint please indicate the source!!


Hibernate core classes and interfaces detailed description

Related Article

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.