Hibernate Core Interface

Source: Internet
Author: User
Tags emit

Configuration (annotationconfiguration)

Role: Management of configuration information

Objective: to generate sessionfactory

Hibernate configuration files can be specified in the Configure method, and the hibernate.cfg.xml file is loaded under Classpath by default (not specified)

To load the default hibernate configuration file

Sessionfactory Factory =new annotationconfiguration (). Configure (). Buildsessionfactory ();

Load the configuration file for the specified hibernate

Sessionfactory factory = newnnotationconfiguration (). Configure ("Hibernate.xml"). Buildsessionfactory ();


Sessionfactory

Function: Mainly used to generate session of the factory (database connection pool)

When it produces a session, it pulls a connection from the database connection pool and hands it to the session

Session session= sessionfactory.getcurrentsession ();

And the connection can be removed through this session.

getcurrentsession (): Indicates that the current environment does not have a session, create one, or do not create a

opensession (): Indicates the creation of a session (not used after 3.0), need to close this session after use

The difference between the two methods:

①, Opensession always open a new session each time, and getcurrentsession is not, is to find from the context, only currently no session, only to create a new session

②, opensession need manual close,getcurrentsession do not need manual close, transaction commit Auto Close

③, getcurrentsession defining transaction boundaries

The context referred to is the value referred to by "Current_session_context_class" in the Hibernate configuration file (Hibernate.cfg.xml): (Desirable value: jta|thread|managed |custom. Class)

<propertyname= "Current_session_context_class" >thread</property>

Commonly used are:

①, Thread: A new session is created from the context and only when there is no session, primarily from the data-defined transaction

②, JTA: primarily from distributed defined transactions, run-time requires Application server support (tomcat not supported)

③, managed: infrequently used

④, Custom. Class: Not used


Session

Save ()

Session.save (Object)

The Save method of the session is to save an object to the database, which produces three states of the object

Delete ()

Session.delete (Object)

Object objects require an ID

Object is transistent state after object is deleted

Load ()

Format: Session.load (classarg0,serializable arg1) throws Hibernateexception

ARG0: The class that needs to load the object, for example: User.class

Arg1: The query condition (the object that implements the serialized interface). If it is a numeric class type, Hibernate automatically uses the wrapper class,

This method returns a type of object, but returns a proxy.

Query SQL statements are not emitted immediately when this method is executed. Only when an object is used, does it emit a query SQL statement that loads the object.

Because the Load method implements lazy (called lazy loading, Raigacai)

Lazy loading: Only when the object is actually used is it loaded (the SQL statement is issued)

Hibernate lazy Load Implementation principle is the proxy mode.

Use the load () method to load the data if there is no corresponding record in the database, the exception object will be thrown (org.hibernate.ObjectNotFoundException)

Get ()

Format: Session.get (classarg0,serializable arg1) method

ARG0: The class that needs to load the object, for example: User.class

Arg1: Query condition (object that implements the serialized interface): If it is a cardinality type, hibernate is automatically converted into a wrapper class

Return value: This method returns a type of object, that is, objects, then forcibly converted to the object to be loaded.

Returns NULL if the data does not exist;

Note: The query SQL statement is issued immediately when this method is executed.

Load () differs from Get ()

① does not behave the same when there is no corresponding record;

②load returns a proxy object that emits an SQL statement when the object's contents are actually used, which requires the session to be open when the object is first used, or an error

③get load directly from the database without delaying loading

Get () and load () are only based on primary key queries, cannot be queried according to other fields, and if you want to query against a non-primary key, you can use HQL

Update ()

① is used to update the detached object, and the update completes to persistent state (all fields are updated by default)

② Update Transient object will error (no ID)

③ update the Transient object with its own set ID (all fields are updated by default)

④persistent the state of the object, as long as the setting of a different value of the field, when the session is submitted, will automatically update (the default update all fields)

⑤ Update a partially updated field (the content of which field is updated in which field is changed)

A) Method 1:update/updatable property

XML: Settings <property> Tags Update property, setting whether to participate in updates when updating

<property name= "name" update= "false"/>

Note: The update value is True (default): Participate in the update, false: Update does not participate in the update

Annotateon: Set @column Updatable property value, true to participate in update, false: Do not participate in the update

@Column (Updatable=false)

Public Stringgettitle () {return title;}

Note: This method is seldom used because it is not flexible

b) Method 2:dynamic-update property

Note: This method is currently only suitable for XML, Jap1.0annotation does not have a corresponding

In the <class> tag in the entity class's mapping file, use the Dynamic-update property, true: Indicates which field has been modified to update which field, the other field is not updated, but the request is the same session (cannot cross the session), If you cross a session, all of the field content is also updated.

<class name= "Com.bjsxt.Student" dynamic-update= "true" >

Code:

@Test public  void TestUpdate5 () {         session session =sessionfactory.getcurrentsession ();      Session.begintransaction ();      Student s= (Student) Session.get (Student.class, 1);      S.setname ("Zhangsan5");      On commit, only the name field is updated because S is persistent state      session.gettransaction (). commit ();      S.setname ("Z4");      Session Session2 =sessionfactory.getcurrentsession ();      Session2.begintransaction ();      When updated, all fields are updated because S is not persistent state      Session2.update (s) at this time;      Session2.gettransaction (). commit (); }

If you need to update the modified part of the field across the session, you need to use the Session.merget () method to merge the field contents

@Test public  void TestUpdate6 () {         session session =sessionfactory.getcurrentsession ();      Session.begintransaction ();      Student s= (Student) Session.get (Student.class, 1);      S.setname ("Zhangsan6");      Session.gettransaction (). commit ();      S.setname ("Z4");      Session Session2 =sessionfactory.getcurrentsession ();      Session2.begintransaction ();      Session2.merge (s);      Session2.gettransaction (). commit ();}

This allows you to implement partial field updates, but this will result in a single SELECT statement, because when the field data is merged, it is necessary to compare the contents of the field to the database for comparison.

c) using HQL (EJBQL) object-oriented query language (recommended)

  @Test public  void TestUpdate7 () {         session session =sessionfactory.getcurrentsession ();      Session.begintransaction ();      Query q =session.createquery ("Updatestudent s sets.name= ' Z5 ' where s.id = 1");      Q.executeupdate ();      Session.gettransaction (). commit ();      

Saveorupdate ()

Hibernate checks if the object already has a corresponding record in the database (refers to the primary key), updates the update, or adds the data save

Clear ()

Clear Session Cache

Either load or get, the cache is first looked up (one cache, also called Session level cache), and if not, the database lookup is removed, and the clear () method is called to force clear session cache

    Session session=sessionfactory.getcurrentsession ();    Session.begintransaction ();    Teacher t = (Teacher) session.load (teacher.class,1);    System.out.println (T.getname ());          Session.clear ();          Teacher t2= (Teacher) session.load (Teacher.class, 1);    System.out.println (T2.getname ());    Session.gettransaction (). commit ();

Note: This will emit two SELECT statements, and if Session.clear () is removed, only one SELECT statement will be issued, since the second load is using an object with ID 1 in the session cache, which is already in the first load to the cache.

Flush ()

Flush is also present in Hibernate, which in fact executes a flush command before Session.commit () in the default case.

Session.flush Features:

Clean up the cache;

Execute SQL (determine that the SQL statement is executed (determine build update, INSERT, DELETE statement, and so on), and then execute the SQL statement. )

Under what circumstances does the session execute flush:

① is executed by default when the transaction commits;

Note: When flush, you can set it yourself, using Session.setflushmode (Flushmode) to specify.

Session.setflushmode (Flushmode);

Enumeration values for Flushmode:

L Flushmode.always: Task An SQL statement that will flush once

L Flushmode.auto: Auto Flush (default)

L Flushmode.commit: Flush only on COMMIT

L Flushmode.manual: Manual flush.

L Flushmode.never: Never flush this option may be used in performance optimizations, such as session fetching data as read-only, so that it does not need to be synchronized with the database

Note: When setting flush mode, you need to set before the session opens the transaction.

② can explicitly call flush;

③ before executing the query, such as: iterate.

Note: If the primary key generation policy is UUID and not generated by the database, then Session.save () does not emit an SQL statement, only flush when the SQL statement is issued, but if the primary key generation policy is native generated by the database, The SQL statement is issued at the same time as the Session.save.

Evict ()

Example: session.evict (user)

Function: Evict the object from the session cache (Entityentries property)

However, when used in conjunction with commit, an exception is thrown

Session =hibernateutils.getsession (); TX =session.begintransaction (); User1 user = NewUser1 (), User.setname ("John Doe"); User.setpassword ("123"); User.setcreatetime (Newdate ());          User.setexpiretime (Newdate ()); Use Hibernate to save the entity class object to the database, because the user primary key generation policy uses the UUID, so after the call completes the save, only the user is included in the session management, the INSERT statement is not issued, but the ID has been generated,              The Existsindatabase status in session is Falsesession.save (user); Session.evict (user);//Evict the object from the session cache (Entityentries property)//Cannot commit successfully because Hibernate is in a temporary collection of sessions (insertions) when it cleans up the cache After removing the user object for an insert operation, you need to update the existsindatabase in the Entityentries property to True, and we used evict to evict the user from the session, so we cannot find the relevant data and cannot update it.          Throws an exception. Tx.commit (); Resolves a method that does not throw an exception in an object that is evicted from the session cache: the call Session.flush () method that is displayed before Session.evict () is ready.              Session.save (user); After flush, hibernate cleans up the cache, saves the user object to the database, and clears the user object from the insertions in the session.          The Existsindatabase status in the session will be set to Falsesession.flush (); Session.evict (user);//Evict the object from the session cache (Entityentries attribute)//can be successfully committed because hibernate is cleaning up the cache, The user object cannot be found in the insertions of the session, so no INSERT statement is issued, norUpdates the status of the Existsindatabase in the session. Tx.commit ();


Hibernate Core Interface

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.