Hibernate connection pool

Source: Internet
Author: User
Package Dao;

Import java. SQL. connection;
Import java. SQL. sqlexception;

Import org. hibernate .*;
Import org. hibernate. cfg. configuration;
Import org. Apache. commons. Logging .*;

/**
* Basic hibernate helper class, handles sessionfactory, session and
* Transaction.
* <P>
* Uses a static initializer for the initial sessionfactory creation and holds
* Session and transactions in thread local variables. All exceptions are
* Wrapped in an unchecked infrastructureexception.
*
* @ Author christian@hibernate.org
*/
Public class jdbcutil {

Private Static log = logfactory. getlog (jdbcutil. Class );

Private Static configuration;

Private Static sessionfactory;

Private Static final threadlocal threadsession = new threadlocal ();

Private Static final threadlocal threadtransaction = new threadlocal ();

Private Static final threadlocal threadinterceptor = new threadlocal ();

Private Static Boolean iscmttransaction = false;
// Create the initial sessionfactory from the default configuration files
Static {
Try {
Configuration = new configuration ();
Sessionfactory = configuration. Configure ("applicationContext-resources-unit.xml"). buildsessionfactory ();
// Checkcmttransaction ();
// We cocould also let hibernate bind it to JNDI:
// Configuration. Configure (). buildsessionfactory ()
} Catch (throwable ex ){
// We Have To catch throwable, otherwise we will miss
// Noclassdeffounderror and other subclasses of error
Log. Error ("Building sessionfactory failed.", ex );
Throw new exceptionininitializererror (Ex );
}
}

/**
* Returns the sessionfactory used for this static class.
*
* @ Return sessionfactory
*/
Public static sessionfactory getsessionfactory (){
/*
* Instead of a static variable, use JNDI: sessionfactory sessions =
* NULL; try {context CTX = new initialcontext (); string jndiname =
* "Java: hibernate/hibernatefactory"; Sessions =
* (Sessionfactory) CTX. Lookup (jndiname);} catch (namingexception ex ){
* Throw new infrastructureexception (Ex);} return sessions;
*/
Return sessionfactory;
}

/**
* Returns the original hibernate configuration.
*
* @ Return Configuration
*/
Public static configuration getconfiguration (){
Return configuration;
}

/**
* Rebuild the sessionfactory with the static configuration.
*
*/
Public static void rebuildsessionfactory () throws exception {
Synchronized (sessionfactory ){
Try {
Sessionfactory = getconfiguration (). buildsessionfactory ();

Checkcmttransaction ();
} Catch (exception ex ){
Throw ex;
}
}
}

/**
* Rebuild the sessionfactory with the given hibernate configuration.
*
* @ Param cfg
*/
Public static void rebuildsessionfactory (configuration CFG)
Throws exception {
Synchronized (sessionfactory ){
Try {
Sessionfactory = cfg. buildsessionfactory ();
Configuration = CFG;
Checkcmttransaction ();
} Catch (exception ex ){
Throw ex;
}
}
}

/**
* Retrieves the current session local to the thread. <p/> if no session is
* Open, opens a new session for the running thread.
*
* @ Return session
*/
Public static session getsession () throws exception {
Session S;
Try {
If (iscmttransaction ()){
If (log. isdebugenabled ()){
Log. debug ("Get currentsession ");
}
S = getsessionfactory (). getcurrentsession ();
} Else {
S = (Session) threadsession. Get ();
If (S = NULL ){
Log. debug ("opening new session for this thread .");
If (getinterceptor ()! = NULL ){
Log. debug ("using Interceptor :"
+ Getinterceptor (). getclass ());
S = getsessionfactory (). opensession (getinterceptor ());
} Else {
S = getsessionfactory (). opensession ();
}
Threadsession. set (s );
}
}
} Catch (hibernateexception ex ){
Throw ex;
}
Return S;
}

/**
* Closes the session local to the thread.
*/
Public static void closesession () throws exception {
// Wocould be written as a no-op in an EJB container with CMT
If (iscmttransaction ()){
Return;
}
Try {
Session S = (Session) threadsession. Get ();
Threadsession. Set (null );
If (s! = NULL & S. isopen ()){
Log. debug ("Closing session of this thread .");
S. Close ();
}
} Catch (hibernateexception ex ){
Throw ex;
}
}

/**
* Closes the connection
* @ Throws infrastructureexception
*/
Public static void closeconnection () throws exception {
Try {
Connection conn = getsession (). Connection ();
If (Conn! = NULL &&! Conn. isclosed ()){
Log. debug ("Closing connection .");
Conn. Close ();
Conn = NULL;
}
} Catch (sqlexception ex ){
Throw ex;
}
}

/**
* Closes the connection
* Closes the session
* @ Throws infrastructureexception
*/
Public static void closeconnectionandsession () throws exception {
Try {
Closesession ();

Closeconnection ();
} Catch (exception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}

/**
* Start a new database transaction.
*/
Public static void begintransaction () throws exception {
// Wocould be written as a no-op in an EJB container with CMT
If (iscmttransaction ()){
Return;
}
Transaction Tx = (transaction) threadtransaction. Get ();
Try {
If (Tx = NULL ){
Log. debug ("starting new Database Transaction in this thread .");
Tx = getsession (). begintransaction ();
Threadtransaction. Set (TX );
}
} Catch (hibernateexception ex ){
Throw ex;
}
}

/**
* Commit the database transaction.
*/
Public static void committransaction () throws exception {
// Wocould be written as a no-op in an EJB container with CMT
If (iscmttransaction ()){
Return;
}
Transaction Tx = (transaction) threadtransaction. Get ();
Try {
If (TX! = NULL &&! TX. wascommitted ()&&! TX. wasrolledback ()){
Log. debug ("committing database transaction of this thread .");
TX. Commit ();
}
Threadtransaction. Set (null );
} Catch (hibernateexception ex ){
Rollbacktransaction ();
Throw ex;
}
}

/**
* Commit the database transaction.
*/
Public static void rollbacktransaction () throws exception {
// Wocould be written as a no-op in an EJB container with CMT (maybe
// Setrollbackonly ...)
If (iscmttransaction ()){
Return;
}
Transaction Tx = (transaction) threadtransaction. Get ();
Try {
Threadtransaction. Set (null );
If (TX! = NULL &&! TX. wascommitted ()&&! TX. wasrolledback ()){
Log
. Debug ("tyring to rollback database transaction of this thread .");
TX. rollback ();
}
} Catch (hibernateexception ex ){
Throw ex;
} Finally {
Closesession ();
}
}

/**
* Reconnects A hibernate session to the current thread.
*
* @ Param session
* The Hibernate session to be reconnected.
*/
Public static void reconnect (session)
Throws exception {
Try {
Session. Reconnect ();
Threadsession. Set (session );
} Catch (hibernateexception ex ){
Throw ex;
}
}

/**
* Disconnect and return Session from current thread.
*
* @ Return session the disconnected session
*/
Public static session disconnectsession () throws exception {

Session session = getsession ();
Try {
Threadsession. Set (null );
If (session. isconnected () & session. isopen ())
Session. Disconnect ();
} Catch (hibernateexception ex ){
Throw ex;
}
Return session;
}

/**
* Register a hibernate interceptor with the current thread.
* <P>
* Every session opened is opened with this interceptor after registration.
* Has no effect if the current session of the thread is already open,
* Valid tive on next close ()/getsession ().
*/
Public static void registerinterceptor (interceptor ){
Threadinterceptor. Set (interceptor );
}

Private Static interceptor getinterceptor (){
Interceptor interceptor = (interceptor) threadinterceptor. Get ();
Return interceptor;
}

Private Static Boolean iscmttransaction (){
Return iscmttransaction;
}

Private Static void checkcmttransaction (){
// Check the configuration is CMT or others
Try {
String factory_class = Configuration
. Getproperty ("hibernate. transaction. factory_class ");
If (factory_class.endswith ("cmttransactionfactory ")){
Iscmttransaction = true;
}
} Catch (exception e ){
Iscmttransaction = false;
}
}
}

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.