Hibernate core interface, hibernate Core

Source: Internet
Author: User

Hibernate core interface, hibernate Core

Configuration (AnnotationConfiguration)

Role: Manage configuration information

Objective: To generate SessionFactory

You can specify the hibernate configuration file in the configure method. It is loaded under classpath by default (not specified ).Hibernate. cfg. xmlFile

Load the default hibernate configuration file

SessionFactory factory = new AnnotationConfiguration (). configure (). buildSessionFactory ();

Load the configuration file of the specified hibernate

SessionFactory factory = newnnotationConfiguration (). configure ("hibernate. xml"). buildSessionFactory ();


SessionFactory

Role: Mainly used to generate Session factories (Database Connection Pool)

When a Session is generated, a connection is retrieved from the database connection pool and handed over to the Session.

Session session =SessionFactory. getCurrentSession ();

And the connection can be retrieved through this Session.

GetCurrentSession (): If the current environment does not have a Session, create one. Otherwise, do not create one.

OpenSession (): Indicates creating a Session (not frequently used after 3.0). You need to disable this Session after use.

Differences between the two methods:

1. openSession always opens a new Session, while getCurrentSession is not. It is found from the context. A new Session is created only when no Session exists.

② OpenSession needs to be closed manually, getCurrentSession does not need to be closed manually, and transaction commit will be closed automatically

③ GetCurrentSession defines the transaction Boundary

The context refers to the"Current_session_context_class": (Optional values: jta | thread | managed | custom. Class)

<Propertyname = "current_session_context_class"> thread </property>

Commonly used:

(1) thread: a new Session is created only when no Session exists in the context. It mainly defines the transaction from data.

②. Jta: mainly defines transactions in a distributed manner, which must be supported by the Application Server during running (not supported by Tomcat)

③. Managed: not commonly used

④ Custom. Class: not commonly used


Session

Save ()

Session. save (Object)

The save method of session is to save an object to the database. This method produces three States of the object.

Delete ()

Session. delete (Object)

The Object must have an ID.

After an object is deleted, its status is Transistent.

Load ()

Format: Session. load (Classarg0, Serializable arg1) throws HibernateException

Arg0: class of the object to be loaded, for example: User. class

Arg1: Query condition (the object that implements the serialization interface ). If it is a numeric type, hibernate will automatically use the packaging class,

This method returns an Object type, but a proxy Object.

When this method is executed, SQL queries are not immediately issued. Only when an object is used can it issue a query SQL statement to load the object.

Because the load method implements lazy (called delayed loading and LAI loading)

Delayed loading: This object is loaded only when it is actually used (an SQL statement is issued)

The implementation principle of hibernate delayed loading is proxy.

Use the load () method to load data. If the database does not have the corresponding records, an exception object will be thrown and cannot be found (org. hibernate. ObjectNotFoundException)

Get ()

Format: Session. get (Classarg0, Serializable arg1) Method

Arg0: class of the object to be loaded, for example: User. class

Arg1: Query condition (object that implements the serialization Interface): If it is a base type, hibernate will automatically convert it to a packaging class.

Return Value: This method returns the Object type, that is, the Object, and then forcibly converts it to the Object to be loaded.

If the data does not exist, null is returned;

Note: When this method is executed, an SQL query statement is issued immediately.

Difference between load () and get ()

① When no corresponding record exists, the performance is different;

② Load returns a proxy object. An SQL statement is issued only when the object content is actually used. This requires that the session be open when the object is used for the first time; otherwise, an error occurs.

③ Get is loaded directly from the database without delay

Get () and load () are only queried based on the primary key and cannot be queried based on other fields. to query based on a non-primary key, you can use HQL

Update ()

① Used to update the detached object. After the update is complete, it is changed to the persistent state (all fields are updated by default)

② An error will be reported when updating the transient object (no ID)

③ Update the transient object with the configured ID (all fields are updated by default)

④ For objects in the persistent state, as long as the values of different fields are set, the object will be automatically updated when the session is submitted (all fields are updated by default)

⑤ Update partially updated fields (update the content of a field if any field is changed)

A) Method 1: update/updatable attributes

Xml: Set the update attribute of the <property> tag, and set whether to participate in the update when the tag is updated.

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

Note: update can be set to true (default): used for update; false: not used for update.

Annotateon: Set the updatable attribute value of @ Column. true indicates update, and false indicates that update is not performed.

@ Column (updatable = false)

Public StringgetTitle () {return title ;}

Note: This method is rarely used because it is not flexible.

B) Method 2: dynamic-update attributes

Note: This method is only applicable to the xml method currently, and there is no corresponding JAP1.0annotation

In the <class> label of the ing file of the object class, use the dynamic-update attribute. "true" indicates that the field is updated when the field is modified, and other fields are not updated, however, it must be the same session (not cross-session). If it is cross-session, all fields will be 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"); // when submitting a request, only the name field is updated because s is in the persistent state session. getTransaction (). commit (); s. setName ("z4"); Session session2 = sessionFactory. getCurrentSession (); session2.beginTransaction (); // All fields are updated when the update is performed, because the s is not in the persistent State session2.update (s); session2.getTransaction (). commit ();}

To update and modify some fields across sessions, use session. merget () to merge the field content.

@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();}

In this way, some fields can be updated, but a select statement will be added, because when the field data is merged, it is necessary to compare whether the field content has changed, you need to retrieve this record from the database for comparison.

C) use the 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 ()

During the execution, hibernate will check that if the object already has a corresponding record (primary key) in the database, the update will be updated; otherwise, the data save

Clear ()

Clear session cache

Both load and get will first find the cache (level-1 cache, also called session-level cache). If no cache is available, the cache will be queried in the database. The clear () method can be called to forcibly clear the 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: In this case, two SELECT statements will be issued. clear () is removed, only one SELECT statement is issued, because the second load is an object with ID 1 in the session cache, this object has been loaded into the cache for the first time.

Flush ()

The flush function also exists in hibernate. By default, a flush command is executed before session. commit.

Session. flush:

Clear cache;

Execute the SQL statement (whether to execute an SQL statement (whether to generate an update, insert, or delete statement) and then execute the SQL statement .)

When is the Session flush:

① The task is executed when the transaction is committed by default;

Note: When flush is enabled, you can set it by yourself and use session. setFlushMode (FlushMode) to specify it.

Session. setFlushMode (FlushMode );

Enumerated values of FlushMode:

L FlushMode. ALWAYS: a SQL statement of the task will be flushed once.

L FlushMode. AUTO: automatic flush (default)

L FlushMode. COMMIT: flush only when commit is used.

L FlushMode. MANUAL: MANUAL flush.

L FlushMode. NEVER: NEVER flush this option may be used in performance optimization. For example, it is used when session data is read-only, so that it does not need to be synchronized with the database.

Note: When setting the flush mode, you must set it before the session starts the transaction.

② You can explicitly call flush;

③ Before executing a query, for example, iterate.

Note: If the primary key generation policy is uuid or not generated by the database, session. saving () does not issue SQL statements. Only flush does. However, if the primary key generation policy is generated by the database by native, session. when saving, an SQL statement is issued.

Evict ()

Example: session. evict (user)

Purpose: evicted from the session cache (EntityEntries attribute ).

However, when used together with commit, an exception is thrown.

Session = HibernateUtils. getSession (); tx = session. beginTransaction (); User1 user = newUser1 (); user. setName ("Li Si"); user. setPassword ("123"); user. setCreateTime (newDate (); user. setExpireTime (newDate (); // use Hibernate to save object class objects to the database. Because the user primary key generation policy uses uuid, after saving is called, 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 the session is falsesession. save (user); session. evict (user); // cache from session (EntityEntries attribute) The object is evicted. // The object cannot be submitted successfully, because when hibernate cleans up the cache, the temporary set of sessions (insertions) after the user object is retrieved from the object, the existsInDatabase in the entityEntries attribute needs to be updated to true, and the evict has evicted the user from the session, so no relevant data can be found and cannot be updated, throw an exception. Tx. commit (); solves the problem of not throwing an exception to an object in the eviction session cache: Call the session. flush () method displayed before session. evict. Session. save (user); // after flushing, hibernate clears the cache, saves the user object to the database, and clears the user object in insertions of the session, the existsInDatabase status in the session is set to falsesession. flush (); session. evict (user); // evict the object from the session cache (EntityEntries attribute). // the object can be successfully submitted because hibernate clears the cache, the user object cannot be found in the insertions collection of the Session, so the insert statement is not issued or the status of existsInDatabase in the session is not updated. Tx. commit ();


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.