Java EE Learning Note ssh-hibernate (4)

Source: Internet
Author: User

Today it's about Hibernate's soul--Session cache

The session cache is composed of a series of Java collections. When an object is added to the session cache, the object's reference is added to the Java collection, and the object is always in the life cycle, even if the reference variable in the application no longer references the object, as long as the session cache is not emptied.

The role of the session cache:

1) Reduce the frequency of access to the database.

2) Ensure that the objects in the cache are kept in sync with the related records in the database.

Session Cleanup Cache Time:

 1)当调用Transaction的commit()方法时,commit()方法先清理缓存(前提是FlushMode.COMMIT/AUTO),然后再向数据库提交事务。 2)当应用程序调用Session的createQuery().list()或者createQuery().iterate()时,如果缓存中的持久化对象的属性发生了变化,就会先清理缓存,以保证查询结果能反映持久化对象的最新状态。    hibernate2中Session.find()对应于3中的session.createQuery().list()    hibernate2中Session.iterate()对应于3中的session.createQuery().iterate() 3)当应用程序显示调用Session的flush()方法的时候。

The Setflushmode () method of the session is used to set the point in time at which the cache is cleaned. The Flushmode class defines three different cleanup modes: Flushmode.auto, Flushmode.commit, and Flushmode.never.
Flushmode.auto is the default value:

session.setFlushMode(FlushMode.COMMIT);

Session cleanup mode a point in time to perform a cleanup cache operation:

Suppose you want to insert two customer information into a database now:

Session session = Hibernatesessionfactory. GetSession();Transaction Transaction = Session. BeginTransaction();Customer customer1 = new Customer (NULL,"Zhang San","78784854","Nanchang");Customer Customer2 = new Customer (NULL,"John Doe","45646463","Beijing");Session. Save(customer1);Session. Save(Customer2);Transaction. Commit();

Two customer objects are created first, and at this point there are two references to two customer objects that point to the heap area in the stack area.

    Customer customer1 = new Customer(null, "张三", "78784854", "南昌");    Customer customer2 = new Customer(null, "李四", "45646463", "北京");

The Save () method is then executed to create two references to the two client objects that refer to the heap area in the session cache, which is a session object. and two insert (insert) statements are generated to remain in the session.

The transaction is committed at the end of the execution to commit (). This is because the session's time to clean up the cache defaults to Flushmode.auto, so when commit () is called Session.flush (), the INSERT statement you just reserved is sent to the database. When commit () is finished, the data for the INSERT statement is persisted in the database.

On the basis of the above, let's look at this code:

Transaction transaction = session.beginTransaction();Customer customer = (Customer) session.load(Customer.class1L);        customer.setName("流川枫");        transaction.commit();

This code is to update the user name of the user with ID 1 to "stream maple". It's strange that this code does not call the update () method, can it be updated? The answer is yes. Now let's take a look at the memory graph:

To analyze the following:

The load () method is executed first, and the corresponding data of the database is loaded into memory, which corresponds to the address B01. At this point the session and the stack area are all pointing to address B01.

Because the Bo1 is a persistent object, and the persistent object changes, the session hears this change and produces a corresponding SQL guarantee that the objects in memory and the data in the database will be consistent after the transaction commits. When you execute to the Coustomer.setname () method, the persisted object changes and the session produces an UPDATE statement. After commit, the UPDATE statement is sent to the database and updated.

So this object does not need to call the update () method to be updated as well.

Then we have to understand what a persistent object is.

Judging the state of an object in Hibernate can be judged from the following two aspects:

A. The relationship between the object and the session

B. Relationships between objects and database data

Hibernate Object Status:

1) instantaneous state transient

The object created by the new operator and not associated with the hibernate session. A Java object that is in a transient state becomes a temporary object.

features :

    不处于Session的缓存中,即不被任何一个Session实例关联。    在数据库中没有对应的记录。

2) Persistent State persistent

has been persisted, added to the session's cache, and the Java object in the persisted state is called a persisted object.

features :

位于一个Session实例的缓存中。持久化对象在数据库中有相应的记录Session在清理缓存时,会根据持久化对象的属性变化来同步更新数据库。当一个持久化对象关联一个临时对象,在允许级联保存的情况下,Session在清理缓存的时候会把这个临时对象也转变为持久化对象。

3) off-pipe state detached

has been persisted, but is no longer in the session's cache, the Java object in the de-state is called a free object.

For example, on the basis of the above, add the following code:

new Customer(1L"""""");

Because a user with ID 1 exists but is not associated with the session, it is a free object.

features :

不再位于Session的缓存中,即不被Session关联。游离对象是由持久化对象转变过来的,因此在数据库存在与之对应的记录(前提是没有其他程序删除了这条记录)

Temporary Objects vs free objects

Same: None is associated with the session, Hibernate does not guarantee that their attribute changes are synchronized with the database.

Different: The former does not have a corresponding record in the database. The latter is transformed by a persistent object, so there may be records in the database that correspond to it.

Hibernate Object state Transition diagram

Off-tube status
Non-maintenance of the pipe-off object in session
Data in the database for a de-tube object

save(obj)     obj 瞬态    将瞬态转化为持久态对象  obj 脱管    重新保存一个新的对象  obj 持久态    没意义update(obj)  obj 脱管    将脱管态转换为持久态saveOrUpdate(obj)  如果obj是瞬态对象,保存  如果obj是脱管对象,更新delete(obj)  将持久态删除

Session API:

The session interface is the most important interface that hibernate provides to the application to manipulate the database, which provides basic methods for saving, updating, deleting, and querying.

Save (): adds a temporary object to the cache, making it a persisted object

-->选用映射文件指定的主键生成器为持久化对象分配唯一的OID-->计划一条insert语句,把参数对象当前的属性值组装到insert语句中,但是save()方法并不立即执行SQL insert语句,只有当Session清理缓存时候才会执行。-->如果在save()方法之后,又修改了持久化对象的属性,会使得Session在清理缓存的时候额外执行SQL update语句。

Note: the Save () method is used to persist a temporary object!

如果将一个持久化对象传给save()方法将不会执行任何操作,多余的步骤如果将一个游离态对象传给save()方法,session会将它当作临时对象来处理,再次向数据库中插入一条记录,不符合业务需求!

update (): The Customer object is re-added to the session cache to make it a persisted object.

--->计划一条update语句,只有在清理缓存的时候才会执行,并且在执行的时候才会把参数对象中的属性值组装到update语句中。

Note: Update () is the conversion of a free object into a persisted object.

  只要通过update()方法使游离对象被一个session关联,即使没有修改参数对象的任何属性,Session在清理缓存的时候也会执行由update方法计划的Update语句。

saveorupdate (): also contains the function of the Save () and update () method, if the passed parameter is a temporary object, call the Save method, if the parameter is a free object, call the update () method, if the object passed in is persisted, return directly.

load ()/get (): a persisted object is loaded from the database based on the given OID, except that the load () method throws a Objectnotfoundexception exception when there is no record in the database corresponding to the OID. The Get () method returns NULL.

Delete (): used to delete the record corresponding to the parameter object from the database, if the passed parameter is a persisted object, the session plans to execute a DELETE statement, if the passed argument is a free object, the free object is associated with the session first, Make it a persisted object, and then schedule a DELETE statement to be executed when the cache is cleaned up.

evict (): clears the persisted object specified by the parameter from the cache.

  适用场合:不希望Session继续按照该对象的状态改变来同步更新数据库。  在批量更新或批量删除的场合,当更新或者删除一个对象后,及时释放该对象占用的内存。当然批量操作优先考虑JDBC.

Clear (): empties all persisted objects in the cache.

Get VS Load

1.get method, hibernate will confirm that the ID corresponds to the existence of the data, first in the session cache to find, and then in the level two cache to find, has not checked the database. The default lazy load, when querying the current object, temporarily does not query the object associated with it.

The Load method, for deferred loading, first puts the query statement into the cache, and then sends the query statements in the cache to the database for querying. (The lazy attribute does not affect it)

Null is returned if the 2.get method is not retrieved

A Org.hibernate.ObjectNotFoundException exception is thrown if the load method is not retrieved

Attention:

Java code

Users user = (Users)session.load(Users.class, userId);  System.out.println(user.getId());  

The above 2 lines of code do not perform database operations. Since load will store a map object in the Hibernate cache, the map key is the value of the UserID, but when you GetID (), it goes to the first-level cache and takes the key value of the map instead of executing the database query. So I won't report anything wrong. Does not perform any database operations.

Additional points:

Cascade

  Cascade Operations, in general who will maintain the relationship, who is cascading.    If the primary table is cascading, and the relationship is maintained from the table, then the error is saved. Save or update (save-update) customer <set name= "Orders" cascade= "save-update"/> This means customer cascade Ord                ER Maintenance Relationship Customer maintains order customer.getorders (). Add (O1);                Customer.getorders (). Add (O2);            Customer.getorders (). Add (O3);                Session.save (customer);                INSERT into tbl_customer values ();                    if (cascade) {OS = Customer.getorders ();                    for (Order O:os) {save (O); Delete (delete) Delete save update (all) dismiss relationship as delete (Delete-orphan): Must contact the relationship, delete the data from the table  
        Customer c = (Customer) session.get(Customer.class4L);        Orderorder = (Order) session.get(Order.class8L);        //接触关系        c.getOrders().remove(order);        order.setCustomer(null);
    删除保存更新,解除关系即删除(all-delete-orphan)

Lazy

默认true  延迟加载,查询当前对象的时候暂时先不查询与之关联的对象false   立即加载,查询当前对象的时候查询所有与之关联的对象。

Inverse (reversal of the right to maintain relations)

一般谁来维护关系谁就来产生外键,不能权利颠倒。如果主表维护从表,而主表的维护关系的权利反转了(即在主表中 inverse="true"),则插入数据的时候不会产生外键即从表中的外键为null。一般1:n关系由多的一方来维护即可。一般写在set中默认false 当前方可以维护关系(产生外键)true        当前方不维护关系(不产生外键)

Java EE Learning Note ssh-hibernate (4)

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.