Gethibernatetemplate (). Method () and getsession (). Method ()

Source: Internet
Author: User
Tags generator generator

Citation source http://shenzhenchufa.blog.51cto.com/730213/156184
I can see an article on the Internet that compares getsession (). Method () and gethibernatetemplate (). Method ().
Some deviations (of course, this is only my personal opinion. Please criticize and correct me if you are right or wrong). I will give my opinion everywhere in the original article. The citation is as follows:

In SSH or SSH2, You can inherit the hibernatedaosupport to operate the database Dao.

There are two implementation methods after inheritance:
Super. getsession (). ();
Gethibernatetemplate (). B ();
Which one is better?
Gethibernatetemplate is recommended online because:
Both getsession () and gethibernatetemplate can automatically release connections (of course, your configuration must be correct), but within a thread,
If you perform many operations at the same time (for example, 1000 queries), getsession will get many sessions (that is, many sessions and connections ),
It is likely that the database connection exceeds the upper limit. Therefore, gethibernatetemplate is recommended.

<--- My opinion is as follows:
If your configuration is spring2 + hibernate2.
Whether it's getsession () or gethibernatetemplate (), tracing will eventually find that they all call
The dogetsession (...) of sessionfactoryutils is first managed locally from transactionsynchronizationmanager.
Check whether a sessionholder exists in the thread variable and whether sessionholder contains the session. If the current thread is not bound to a session
Session variable, a new session variable is created as follows:

/**
* Get A hibernate session for the given sessionfactory. is aware of and will
* Return any existing corresponding session bound to the current thread,
* Example when using {@ link hibernatetransactionmanager}. will create a new
* Session otherwise, if "allowcreate" is <code> true </code>.
* <P> same as {@ link # getsession}, but throwing the original hibernateexception.
* @ Param sessionfactory hibernate sessionfactory to create the session
* @ Param entityinterceptor hibernate entity interceptor, or <code> null </code> If none
* @ Param jdbcexceptiontranslator sqlexcepiontranslator to use for flushing
* Session on transaction synchronization (may be <code> null </code>)
* @ Param allowcreate whether a non-transactional session shoshould be created
* When no transactional session can be found for the current thread
* @ Return the hibernate session
* @ Throws hibernateexception if the session couldn't be created
* @ Throws illegalstateexception if no thread-bound session found and
* "Allowcreate" is <code> false </code>
*/
Private Static session dogetsession (
Sessionfactory, interceptor entityinterceptor,
Sqlexceptiontranslator jdbcexceptiontranslator, Boolean allowcreate)
Throws hibernateexception, illegalstateexception {

Assert. notnull (sessionfactory, "No sessionfactory specified ");

Sessionholder = (sessionholder) transactionsynchronizationmanager. getresource (sessionfactory );
If (sessionholder! = NULL &&! Sessionholder. isempty ()){
// Pre-bound hibernate session
Session session = NULL;
If (transactionsynchronizationmanager. issynchronizationactive ()&&
Sessionholder. doesnotholdnondefasession SESSION ()){
// Spring transaction management is active->
// Register pre-bound session with it for transactional flushing.
Session = sessionholder. getvalidatedsession ();
If (session! = NULL &&! Sessionholder. issynchronizedwithtransaction ()){
Logger. debug ("registering Spring transaction synchronization for existing hibernate session ");
Transactionsynchronizationmanager. registersynchronization (
New springsessionsynchronization (sessionholder, sessionfactory, jdbcexceptiontranslator, false ));
Sessionholder. setsynchronizedwithtransaction (true );
// Switch to flushmode. Auto, as we have to assume a thread-bound session
// With flushmode. Never, which needs to allow flushing within the transaction.
Flushmode = session. getflushmode ();
If (flushmode. lessthan (flushmode. Commit )&&
! Transactionsynchronizationmanager. iscurrenttransactionreadonly ()){
Session. setflushmode (flushmode. Auto );
Sessionholder. setpreviusflushmode (flushmode );
}
}
}
Else {
// No Spring transaction management active-> try JTA transaction synchronization.
Session = getjtasynchronizedsession (sessionholder, sessionfactory, jdbcexceptiontranslator );
}
If (session! = NULL ){
Return session;
}
}

Logger. debug ("Opening hibernate session ");
Session session = (entityinterceptor! = NULL?
Sessionfactory. opensession (entityinterceptor): sessionfactory. opensession ());

// Use same session for further hibernate actions within the transaction.
// Thread object will get removed by synchronization at Transaction completion.
If (transactionsynchronizationmanager. issynchronizationactive ()){
// We're within a spring-managed transaction, possibly from jtatransactionmanager.
Logger. debug ("registering Spring transaction synchronization for new hibernate session ");
Sessionholder holdertouse = sessionholder;
If (holdertouse = NULL ){
Holdertouse = new sessionholder (session );
}
Else {
Holdertouse. addsession (session );
}
If (transactionsynchronizationmanager. iscurrenttransactionreadonly ()){
Session. setflushmode (flushmode. Never );
}
Transactionsynchronizationmanager. registersynchronization (
New springsessionsynchronization (holdertouse, sessionfactory, jdbcexceptiontranslator, true ));
Holdertouse. setsynchronizedwithtransaction (true );
If (holdertouse! = Sessionholder ){
Transactionsynchronizationmanager. bindresource (sessionfactory, holdertouse );
}
}
Else {
// No Spring transaction management active-> try JTA transaction synchronization.
Registerjtasynchronization (Session, sessionfactory, jdbcexceptiontranslator, sessionholder );
}

// Check whether we are allowed to return the session.
If (! Allowcreate &&! Issessiontransactional (Session, sessionfactory )){
Closesession (session );
Throw new illegalstateexception ("No hibernate session bound to thread," +
"And configuration does not allow creation of Non-transactional one here ");
}

Return session;
}

Therefore, if a thread is not included in the transaction, getsession () and gethibernatetemplate () are the same, and each call to them will
Create a session and a new connection.

If they have been included in a transaction, they both use the same session and connection.
I think the above statement (getsession will get many sessions, that is, opening many sessions and connecting are likely to cause the database connection to exceed the upper limit.
Therefore, gethibernatetemplate is recommended .) No.
--->
 
(1 )------------------------------------------
Getsession usage:
Query:
Super. getsession (). Find ()
Super. getsession (). createquery ()
Save:
Super. getsession (). Save ()
Super. getsession (). Update ()
Super. getsession (). Delete ()

Query usage:
Select, update, delete, and paging can be executed through query:
-1-> the benefit of using query can be set like preparedstatement.
-2-> and does not use iterate, because it only determines whether there is any value, so use list. size () is determined. If there is a value, there is only one, that is, it can be obtained using List (0 ).
-3-> at the same time, query can be used not only for queries, but also for updates:
String hql = "update user set userpwd =? Where userid =? ";
Query q = super. getsession (). createquery (hql );
Q. setstring (0, userpwd );
Q. setstring (1, userid );
Q.exe cuteupdate ();
-4-> delete:
String hql = "delete from item where Itemid =? ";
Query q = super. getsession (). createquery (hql );
Q. setinteger (0, Itemid );
Q.exe cuteupdate ();
-5-> paging with query:
List all = NULL;
String hql = "from question as Q where Q. Itemid =? ";
Query q = super. getsession (). createquery (hql );
Q. setinteger (0, Itemid );
Q. setfirstresult (currentpage-1) * linesize );
Q. setmaxresults (linesize );
All = Q. List ();
For example:
Query query = session. createquery ("from user ");
Query. setfirstresult (0); // starts from the first record
Query. setmaxresults (4); // retrieve four records
List userlist = query. List ();

(2 )------------------------------------------
Hibernatetemplate:
Common Methods of hibernatetemplate:
Void Delete (Object entity): deletes a specified persistent instance.
Deleteall (Collection entities): deletes all persistent class instances in the set.
Find (string uerystring): returns an instance set based on the HL query string.
Findbynameduery (string ueryname): returns the instance set based on the name query.
Get (class entityclass, serializable ID): loads instances of specific persistence classes based on primary keys.
Save (Object entity): Save the new instance
Saveorupdate (Object entity): select Save or update based on the instance status.
Update (Object entity): update the instance status, requiring the entity to be persistent
Setmaxresults (INT maxresults): sets the page size.
 
Examples of common methods:
Query:
// Use the find method of hibernatetemplate to return all instances of person --> the return value is list type.
Return gethibernatetemplate (). Find ("from person ");
// Query with Parameters
Use this method to find (string hql, object para) --> the returned result is of the list type.
String hql = "select U. Username from user u where u. Username =? ";
List userlist = This. gethibernatetemplate (). Find (hql, user. GetUserName ());
// Return a specific instance based on the primary key --> Primary Key query --> return an object type
Return (person) gethibernatetemplate (). Get (person. Class, new INTEGER (personid ));
Return (person) gethibernatetemplate (). Load (person. Class, new INTEGER (personid ));
// Saved person instance
Gethibernatetemplate (). saveorupdate (person );
// Delete the primary key of the person instance
// Load a specific instance first
Object P = gethibernatetemplate (). Load (person. Class, new INTEGER (personid ));
// Delete a specific instance
Gethibernatetemplate (). Delete (P );
 
Description of the hibernate primary key generator Generator
1. If the primary key field is of the auto-increment type.
The XML Declaration of the ID field in the corresponding. HBM. xml file,
It should be written as follows:
<Generator class = "native"/>
For example:
<ID column = "user_id" name = "ID" type = "integer">
<Generator class = "native"/>
</ID>
2. If the primary key field is not set to auto-increment, it is of the int type.
You can use increment to generate a primary key from hibernate.
<Generator class = "increment"/>
However, this method does not seem recommended for applications with a large concurrency.
3. If UUID. Hex is used to generate a random 32-digit primary key.
The ID field type of the database is Char and the length is 32.
Written in HBM. XML as: <generator class = "UUID. Hex"/>
In addition, the UUID. String function is similar.
UUID. HEX generates a 32-bit hexadecimal number string.
UUID. String generates a string consisting of 16 characters and any ASCII characters.
See references:
UUID. HEX
Use a 128-bit UUID algorithm to generate string-type identifiers. It is unique in a network (using an IP address ). UUID is encoded as a 32-bit hexadecimal number string.
UUID. String
Use the same UUID algorithm. UUID is encoded as a string consisting of 16 characters long and any ASCII characters. Cannot be used in a PostgreSQL database

 

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.