Hibernate core classes and interfaces

Source: Internet
Author: User

Hibernate core classes and interfaces

 

I. hiobernate core class and interface Preview

Ii. hibernate. properties

This file is similar to the hibernate. cfg. xml file used in earlier versions. It is used in the same way as hibernate. cfg. xml.

Iii. hibernate. cfg. xml (1) Details

① This file is mainly used to specify parameters and is the core file of hibernate.
② It is stored in the src directory by default, or in another directory.
③ Specify the driver, user name, password, url, and connection pool used to connect to the database ..
④ Specify the location of the object link ing file.
⑤ You can also use the hibernate. properties file to replace this file. (hibernate. cfg. xml is recommended ).

(2) configuration file template
 
 
 
  
   
   
    
Com. mysql. jdbc. Driver
   
   
    
Root
   
   
    
Xu827928
   
   
    
Jdbc: mysql: // MAID: 3306/hbmtest
   
   
   
    
Org. hibernate. dialect. MySQLDialect
   
   
   
    
True
   
   
   
    
True
   
   
   
   
   
    
Update
   
   
   
  
 

 

Iv. *. hbm. xml

 

(1) object relationship ing file (*. hbm. xml) ① this file is mainly used to establish the ing between tables and classes and is an indispensable and important file.
② It is generally placed in the same directory of the ing class, but it is not necessary.
③ The naming method is generally the class name. hbm. xml, but not required.

 

④:

(2) configuration file template
 
 
 
 
  
   
   
     
    
   
   
   
    
   
   
    
   
   
    
   
  
 

V. Configuration class (1) Details

① Manages the configuration information of hibernate.
② Read hibernate. cfg. xml
③ Load the driver, url, user name, password, and connection pool configured in the hibernate. cfg. xml configuration file.
④ Manage *. hbm. xml Object Relational files.

(2) sample code: Configuration cf = new Configuration (). configure ();

Vi. SessionFactory interface (1) Details

 

① Cache SQL statements and some data

② It is created during application initialization and is a heavyweight class (eat memory). Generally, the singleton mode ensures that only one SessionFactory instance is required for an application.

③ If an application accesses multiple databases, multiple session factory instances are created. Generally, one database is a session factory instance.
④ Session instances can be obtained through the SessionFactory interface.

 

(2) sample 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 an operation with the database (of course, one operation can be a combination of crud)

② The Session instance is obtained through SessionFactory and needs to be closed after use.
③ The Session is not synchronized by the thread (unsafe). Therefore, you can use getCurrentSessiong () to ensure that the Session is used in the same thread ().
④ Session can be viewed as a persistence manager, which is an interface related to persistence operations.

(2) sample code:
Configuration cf = new Configuration (). configure (); SessionFactory sf = cf. buildSessionFactory (); Session s = sf. getCurrentSession (); // or: Session s = sf. openSession ();
(3) Several important methods of the Session Interface

Sessions are generally operated in the form of objects.
Let's demonstrate it to you! (Please refer to the document)
① Save an object (record)-save Method
② Delete an object (record)-delete Method
③ Query an object (record)-get/load Method
④ Modify an object (record)-update Method

(4) Difference between get () and load ()

1. The get () method returns the object class directly. If no data is found, null is returned. Load () will
Returns an object proxy object (the current object can be automatically converted to an object ),
However, when a contemporary object is called, if no data does not exist,
Org. hibernate. ObjectNotFoundException exception


2. load first goes to the cache (session cache/second-level cache). If no,
Proxy object (not immediately in the database), when this proxy object is used later
Wait, to query in the DB. This is what we often say is that load supports latency addition by default.
Load (lazy)


3. get goes to the cache (session cache/second-level cache) first. If not, go to the database.
Query (that is, issue the SQL statement immediately ). In short, if you are sure that the database has this object, you can use
Load (), use get () If you are not sure (this is highly efficient)

Load VS get

 

1. If no data is found, get will return null, but no error will be reported. If load cannot query data, the error ObjectNotFoundException will be reported.

2. when you use get to query data (first-level or second-level), a query request (select...) will be sent to the database immediately ...), if you are using load to query data (first-level, second-level), even if an object is queried, a proxy object is returned. If no query result is returned, it does not actually send a select statement to the database. It is called lazy when programmers use the query results)

3. By modifying the configuration file (*. hbm. xml file), we can cancel lazy loading.

 

 

 

4. How to choose which one to use: If you are sure that the database has this object, load () is used. If you are not sure, get () is used (this is highly efficient)

(5) differences between openSession () and getCurrentSession ()

① Sessions created using getCurrentSession () will be bound to the current thread, while sessions created using openSession () will not

② Sessions created using getCurrentSession () are automatically closed during commit or rollback, while those created using openSession () must be closed manually.
③ To use getCurrentSession (), you must add it to the hibernate. cfg. xml file.

The configuration is as follows:
* If you are using a local transaction (jdbc transaction)
Thread
* If you are using a global transaction (jta transaction)
Jta
 

(6) Contact openSession () and getCurrentSession ()

In-depth discussion:
When SessionFactory is started, Hibernate will create the corresponding CurrentSessionContext according to the configuration. When getCurrentSession () is called, the actual method to be executed is CurrentSessionContext. currentSession ().

When currentSession () is executed, if the current Session is empty, currentSession will call the openSession of SessionFactory.

(7) who should I choose from openSession () and getCurrentSession?

 

Principles:
① If you want to use the same Session in the same thread, use getCurrentSession ()
② If different sessions are required in a thread, use opentSession ()

(8) Contact openSession () and getCurrentSession () and manage the Session in ThreadLocal mode (thread local variable mode). The Code is as follows:

 

public class HibernateUtil {public static final ThreadLocal session =new ThreadLocal();public 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 will briefly explain what a Transaction is.

Transactions are simply a set of database operations. They are either all successful or all failed. This ensures data consistency and atomicity.
① Transaction is the abstract interface in the underlying implementation of things
② It may be a jdbc or jta transaction, which facilitates the migration of hibernate in different execution environments.
③ Call transactions required by hibernate (if only query is required, no call is allowed .)

Transaction ts = s. beginTransaction ();
...
Ts. commit (); s. close (); ts. rollback () is required to roll back when an exception occurs.

(2) global transactions and local transactions: transactions for one database; (jabc transactions) all transactions: Cross-database transactions (jta transactions );
If you want to use getCurrentSession, You need to configure it in the hibernate. cfg. xml file. * if you are using a local transaction (jdbc transaction)
Thread
* If you are using a global transaction (jta transaction)
Jta
9. Query interface

(1) An object of the Query interface type can operate on a database. It can operate on a database using Hql, Qbc, Qbe, and native SQL. Hql statements are officially recommended.

10. Criteria Interface

The Criteria interface can also be used for Object-Oriented queries.
I will not introduce it here. Let's look at a few cases.
Simplest case: return 50 records

Criteria crit = sess.createCriteria(Cat.class);crit.setMaxResults(50);List cats = crit.list();
Restrict result set content
List cats = sess.createCriteria(Cat.class)  .add( Restrictions.like(name, Fritz%) )  .add( Restrictions.between(weight, minWeight, maxWeight) )  .list();

 

 

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.