Persistence class: An entity class that establishes a mapping with a database table.
Hibernate in order to facilitate the management of persistent classes, the persistence class is divided into three states.
Transient state Transient:(temporary State) features: Persistent objects do not have a unique identifier OID. Management without a session
Persistent state persistent: Features: persistent objects have a unique identifier OID. Management that has been included in the session
Off-state detached:(off-line state) features: Persistent objects have a unique identifier OID, not included in the session management
1. Distinguish the state of three persistent objects
Take a look at the following example:
@Test
//distinguish three states of persisted objects: public
void Demo1 () {
//1. Creating session Session Session
= Hibernateutils.opensession ();
2. Turn on transaction
Transaction tx = Session.begintransaction ();
Save a book to the database: Books
= new (); Transient state: There is no uniquely identified OID and is not associated with the session.
Book.setname ("hiernate development");
Book.setauthor ("Sun xx");
Book.setprice (65d);
Session.save (book); Persistent state: Has a uniquely identified OID, which is associated with the session.
3. Transaction submission
Tx.commit ();
4. Release of resources
Session.close ();
Book.setname ("Struts2 development"); Off-state: There is a unique identifier, not associated with the session.
}
2. Three state object conversions:
instantaneous state:
Get:
Book book = new book ();
Instantaneous state-to-last state:
Save (book);
Save ()/saveorupdate ();
Instantaneous state-to-off state:
Book.setid (1);
Persistent State:
Get:
Book book = (book) session.get (book.class,1);
Get ()/load ()/find ()/iterate ();
Persistent state-to-instantaneous state:
Delete (book);
Special status: Delete state. (Deleted objects are not recommended to use.)
Persistent---off-pipe state:
Session.close ();
Close ()/clear ()/evict ();
off-pipe state:
Get:
Book book = new book ();
Book.setid (1);
Off-state---persistent state:
Session.update ();
Update ()/saveorupdate ()/lock ()
Off-state-instantaneous state:
Book.setid (NULL);
Persistent objects have the ability to automatically update the database, for example:
@Test
//test Persistent state objects automatically update the database public
void Demo2 () {
//1. Create session Session Session
= Hibernateutils.opensession ();
2. Turn on transaction
Transaction tx = Session.begintransaction ();
Gets the object of a persistent state.
Book book = (book) session.get (Book.class, 1);
Book.setname ("Struts2 development");
Session.update (book);
3. Submission of transaction
Tx.commit ();
4. Close Resource
session.close ();
}
The ability to automatically update a database relies on Hibernate's first-level cache. We'll show you a bit more about the first-level cache and the level two cache.