Hibernate Session Summary

Source: Internet
Author: User

Hibernate must first obtain the session instance before performing operations on the database, which is equivalent to obtaining the connection instance before performing operations on the database by JDBC. session is the basis for hibernate operations, it is not designed as thread-safe. A session is used by one thread.

  • Enable session
The session instance is obtained by enabling sessionfactory. For example:
Configuration config = new Configuration().configure();SessionFactory sessionFactory = config.buildSessionFactory();Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();....tx.commit();session.close();

Enable session will not get the connection immediately, but will get the connection only after the connection database is updated or queried. If a connection pool is set, the connection will be obtained from the connection pool, when session is closed, if a connection pool is set, the connection is returned to the connection pool, rather than directly closing the connection.

In hibernate, when a session is enabled, a persistence context is created, which can be used for Cache Management, dirty check, and other actions, including reading, updating, and inserting, it is completed in transaction.


  • Store Data

Through session, you can add, delete, and update databases. For example, you can use save () to add a new item:
User user = new User(); user.setName("momor"); user.setAge(new Integer(26));Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();session.save(user); tx.commit();session.close();

After saving (), the database will not be updated immediately, but will be updated only after the Commit () of transaction. All operations between transactions will be successful, if the update fails, all update operations will be revoked at the database level. However, persistent objects in the memory will not return to the original state. In fact, when the transaction fails, this session will immediately expire, giving up all the objects in the memory, instead of trying to update the original object.


  • Obtain information
You can use the get () or load () method to obtain information with ID 1:
Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();User user = (User) session.get(User.class, new Integer(1));tx.commit();session.close();

If the relevant information is not found, the get () method returns NULL, while the load () method throws objectnotfoundexception. In advanced applications, load () the proxy object can be returned, and the database can be queried only when necessary to obtain the corresponding information, and the cache mechanism can be fully utilized.

In hibernate 3, the find () method is canceled, and you must query data through query or criteria.


  • Delete Materials
Next, let's take a look at using session to delete data. You can use Delete () to delete data:

Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();User user = (User) session.get(User.class, new Integer(1));session.delete(user);tx.commit();session.close();

  • Update Materials
When you extract data from the same session and encapsulate it as a persistence object, update the object status, and then modify the transaction commit, the status update on the object will be reflected to the database, you do not need to perform any update operations.

If you have enabled a session, the information is displayed on the user interface in the data table, and then the session is closed. When the user completes the operation on the interface and presses the Save button, in this case, you need to restart a session and use the update () method to update the data in the object to the corresponding data table:

Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();User user = (User) session.get(User.class, new Integer(2));tx.commit();session.close();....user.setAge(new Integer(27));session = sessionFactory.openSession();    tx= session.beginTransaction(); session.update(user);tx.commit();session.close();


Session provides a saveorupdate () method to provide a unified operation interface for data storage or update. When you define a ing file, set the unsaved-value of the <ID> label to determine what is new and what is an existing value must be updated:
<ID name = "ID" column = "ID" type = "Java. Lang. Integer" unsaved-value = "null">
<Generator class = "native"/>
</ID>

Unsaved-value can be set:
  • Any: always stored
  • None: always updated
  • Null: storage when ID is null (preset)
  • Valid: stored when ID is null or a specified value

After this setting, you can use the saveorupdate () method of the session to replace the update () method.


  • Merge status
Here is an example:

Session session = sessionfactory. opensession (); transaction Tx = session. begintransaction (); User user1 = (User) session. get (user. class, new INTEGER (2); Tx. commit (); Session. close ();.... user1.setage (New INTEGER (27); Session = sessionfactory. opensession (); Tx = session. begintransaction (); User user2 = (User) session. get (user. class, new INTEGER (2); // The same ID // user1 = user2 is falsesession. update (user1); // discard nonuniqueobjectexceptiontx. commit (); Session. close ();


Before update (), you can obtain another item from the database and then update user1. Since the current persistence context has loaded a piece of information, if a user instance has the same ID, the same persistence context does not have two object instances with the same ID, so nonuniqueobjectexception is thrown.

For example, you should use Merge () instead of update ():

Session session = sessionfactory. opensession (); transaction Tx = session. begintransaction (); User user1 = (User) session. get (user. class, new INTEGER (2); Tx. commit (); Session. close ();.... user1.setage (New INTEGER (27); Session = sessionfactory. opensession (); Tx = session. begintransaction (); User user2 = (User) session. get (user. class, new INTEGER (2); // The same iduser user3 = (User) session. merge (user1); // user1 = user2 is false // user2 = user3 is truetx. commit (); Session. close ()

;


Merge () merges the statuses of user1 and user2. the returned object instance is the instance referenced by user2.

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.