Hibernate introduction, hibernate

Source: Internet
Author: User

Hibernate introduction, hibernate
I. Overview

Hibernate is an open source object link ing framework. It encapsulates jdbc and provides a powerful and high-performance persistence service for object relational model databases. The HQL (Hibernate Query Language) provided by Hibernate is an Object-Oriented Query Language. It builds a fast, efficient, and convenient communication channel between object model data and relational databases.

Ii. Hibernate framework

1. ORM (Object Relation Mapping) is called Object relationship ing.

When writing a program, data is processed in an object-oriented manner. when data is stored, it is stored in a database in the form of relational data, therefore, we need a mechanism for data conversion between the two. This mechanism is called the object-link ing mechanism (ORM for short.

2. Object status

> Free state

The free state is that the object exists freely in the memory. In this case, it has nothing to do with the database. The Free State has two features:

(1). It is not in the Session cache, that is, it is not associated with any Session instance.

(2). There is no corresponding record in the data.

> Persistent state

The persistent State is the State of the object under the management of Hibernate. In the persistent state, object references are included in the Hibernate object container for management. Objects in the persistent state are solidified into the database by Hibernate. Persistence status features:

(1). stored in the cache of a Session instance. That is to say, persistent objects are always associated with a Session instance.

(2). the persistence object corresponds to the relevant records in the database.

(3) When the Session clears the cache, it synchronously updates the database based on the attribute changes of the Persistent Object.

(4). the Save () method of the Session changes the object from the Free State to the persistent state.

(5). The object returned by the load () method or get () method of the Session is always persistent.

(6) the update (), saveOrUpdate (), and lock () Methods of the Session enable the object to change from a free state to a persistent state.

> Free state

When the corresponding Session of an object in the persistent state is closed, the object is in the Free State. It can be considered that the Session object is the host of the object in the persistent state, the entity object loses the host, that is, the host fails, and the object is in the Free State. Free Status features:

(1). The object is no longer in the Session cache. It can also be said that the object in the Free State is not associated with the Session.

(2). the Free State is changed from persistence, so there may be records corresponding to it in the database.

3. VO and PO

A real Object in a free or free state is called a Value Object (VO ).

Object in the Persistent state is called a Persistent Object (PO ).

Differences between VO and PO:

1. The VO object contains two states: free and free. It is a relatively independent object and is in an unmanaged state.

2. The PO object is persistent. It is the object that Hibernate includes in its management container. It corresponds to the Hibernate object of a record in the database. Changes in the PO will be reflected in the database when the transaction is committed.

3. If a PO is separated from its corresponding Session instance, it will become VO.

Iii. Session management

Session interface is the most important interface that Hibernate provides to applications for database operations. It provides basic methods for saving, updating, deleting, and loading Java objects.

The Session is created by SessionFactory, and the implementation of SessionFactory is thread-safe. That is to say, multiple concurrent threads can simultaneously access one SessionFactory and obtain the Session instance from it, however, the Session is not thread-safe. The Session contains information about database operations. Therefore, data sharing confusion occurs when multiple threads share a Session.

3.1 solve the Session Sharing Problem in ThreadLocal Mode

ThreadLocal is not a Local implementation of a Thread, that is, it is not a Thread, but a Local Variable of the Thread ). It provides a copy of the variable value for every thread that uses this variable, and each thread can change its own copy independently without conflict with the copies of other threads, from the thread perspective, it is like every thread has a variable.

ThreadLocal will provide a copy of the variable to each thread to achieve Session sharing within the thread range, so as to avoid frequent thread creation and destruction of the Session. However, you need to manually close the thread after use.

Package com. test; import java. util. iterator; import java. util. list; import org. hibernate. hibernateException; import org. hibernate. query; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. cfg. configuration; public class LoginDao {private Session session = null; private Transaction tran = null; private static final ThreadLocal <Session> s = new Th ReadLocal <Session> (); // use ThreadLocal to manage Sessionpublic LoginDao () {Configuration config = new Configuration (). configure (); SessionFactory factory = config. buildSessionFactory (); // this. session = factory. openSession (); this. session = s. get (); // call the get method of ThreadLocal to get sessionif (session = null) {this. session = factory. openSession (); // this. session = factory. getCurrentSession (); // to use this method, you need to add the corresponding configuration information s in the configuration file. set (session );// Put the session to ThreadLocal for management}/*** insert data */public void save (Login login) {try {tran = session. beginTransaction (); this. session. save (login); // submit transaction tran. commit (); System. out. println ("user information saved successfully");} catch (RuntimeException e) {if (tran! = Null) {tran. rollback (); // throw e; e. printStackTrace () ;}} finally {this. session. close () ;}/ ***** update operation */public void update (Login login) {try {tran = session. beginTransaction (); session. update (login); tran. commit (); System. out. println ("updated successfully");} catch (HibernateException e) {if (tran! = Null) {tran. rollback (); // throw e; e. printStackTrace () ;}} finally {this. session. close () ;}/ ***** delete operation * @ param login */public void delete (Login login) {try {tran = this. session. beginTransaction (); session. delete (login); tran. commit (); System. out. println ("deleted successfully");} catch (HibernateException e) {if (tran! = Null) {tran. rollback (); // throw e; e. printStackTrace () ;}} finally {this. session. close () ;}/ *** precisely query by primary key **/public Login getLoginByid (String name) {Login login = null; string hql = "from Login as l where l. username =? "; Query query = this. session. createQuery (hql); query. setString (0, name); Iterator list = query. list (). iterator (); if (list. hasNext () {login = (Login) list. next ();} System. out. println ("precise primary key query"); this. session. close (); return login;} public List queryAll () {List list = null; String hql = "from Login as l"; Query query = this. session. createQuery (hql); list = query. list (); System. out. println ("query all records"); this. session. close (); retu Rn list;}/*** perform fuzzy search based on user name */public List queryLike (String name) {List list = null; String hql = "from Login l where l. username like? "; Query query = this. session. createQuery (hql); query. setString (0, "%" + name + "%"); list = query. list (); System. out. println ("fuzzy query"); this. session. close (); return list ;}}
3.2 openSession () and getCurrentSession () Parsing

In addition to providing openSession () to return Session, the SessionFactory class of Hibernate also provides the getCurrentSession () method, which is added after Hibernate version 3.0.1, you can obtain a Session through this method, but the two methods are different. The differences between them are as follows:

1. The Session created by getCurrentSession () is bound to the current thread, but not openSession.

2. The Session created by getCurrentSession () is automatically closed after the transaction is rolled back or submitted, while the Session created by openSession () must be closed manually (the close () method of the called Session)

Note:

(1) When using a local transaction (jdbc transaction), add the following code to the <session-factory> node in the Hibernate. cfg. xml file:

<Property name = "hibernate. current_session_context_class"> thread </property>

(2) When using a global transaction (JTA transaction), add the following code to the <session-factory> node in the hibernate. cfg. xml file:

<Property name = "hibernate. current_session_context_class"> jta </property>

If you use the getCurrentSession () method without adding the above content to the configuration file, the compilation will not report an error, but an error will occur when running the program, "No CurrentSessionContext configured !", In addition, because you do not need to manually close the Session when using the getCurrentSession () method, you do not need to call the close () method of the Session.

3.3. Session usage

3.3.1 save () method

The Save () method of Session converts a free object (also called a temporary object) to a persistent object. To call the save () method of a Session, you need to complete three tasks:

1. Add the object to the Session cache to make it persistent.

2. Select the identifier generator specified by the ing file to assign a unique OID to the persistence object.

3. Execute an insert statement to load the current attribute value of the object to the insert statement.

Note that after the save () method, the attributes of the Persistent object are modified before the commit () method of the transaction. When the session is being cleared, an additional SQL update operation is executed.

User user = new User();user.setPassword("123");user.serUsername("xiazhongwei");Session session = sessionFactory.openSession();Transaction tran = session.beanTransaction();session.save(user);user.setPassword("456");tran.commit();session.close();

Article 1: inser into USER (ID, USERNAME, PASSWORD) values (1, "xiazhongwei", "123 ");

Article 2: update user set username = "xiazhongwei", PASSWORD = "456" where id =?

3.3.2 persist () method

The persist () method is similar to the save () method, and can also change a free object to a persistent object.

Note that the persist () method appears in hibernate3 and implements the persistence semantics defined in the EJB3 specification. When you call the persist () method, not necessarily assign values to the oid of the persistence object immediately, but may assign values to the oid only when the Session is cleared. In addition, when the persist () method is called outside the transaction boundary, this method does not plan to execute an insert statement ..

3.3.3. update () method

Execute the update method of the session to change a free object to a persistent object and execute an update statement. The following operations are completed:

1. Add the free object to the cache of the current session to make it a persistent object.

2. Execute an update statement.

3. The update statement is executed only when the Session clears the cache, and the update statement is executed only once when the data of the object is modified multiple times.

3.3.4 saveOrUpdate () method

If a temporary object is passed in, the save () method is called. If a free object is passed in, the update method is called. If a persistent object is passed in, the system returns the object directly.

3.3.5 load () method

The method is to load a persistent object from the database based on the given OID. The load () method runs out of the org. hibernate. ObjectNotFoundException exception when there is no record corresponding to the oid in the database.

3.3.6. get () method

The get () method is similar to the load () method, where the persistence object is retrieved using the oid. When the get () method does not exist in the database, the get () method returns null.

Another difference between the load () method and the load () method is that the two adopt different retrieval policies. By default, all persistent objects use a delayed loading policy. <class name = "com. entity. user "table =" USER "lazy =" true "> If the lazy attribute is not added, the default value is true. If the lazy attribute is changed to false, the load () method is loaded immediately. However, the get () method ignores the lazy attribute of the class element. That is to say, the get () method uses an immediate loading policy regardless of the value written by the lazy attribute.

So when should I use load and get?

(1) If you load an object to access its attributes, you can use the get () method.

(2) If an object is loaded to delete it or the association between the resume and other objects, you can use the load () method.

3.3.7. delete () method

The delete () method can delete persistent objects or free objects. When the delete () method is called, if the input parameter is a free object, first, the free object is associated with the current session to change the free object to a persistent object. If the parameter is passed into the Persistent object, this step is ignored.

The delete () method also executes a delete statement when the session clears the cache.

 

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.