Code: My commonly used hibernateutil class, hey
- Public final class hibernateutil {
- Private Static sessionfactory;
- Private hibernateutil (){
- }
- // Initialization
- Static {
- Configuration CFG = new configuration ();
- Cfg. Configure ();
- Sessionfactory = cfg. buildsessionfactory ();
- }
- Public static sessionfactory getsessionfactory (){
- Return sessionfactory;
- }
- Public static session getsession (){
- Return sessionfactory. opensession ();
- }
- }
The above is the hibernateutil of a single database. The hibernate. cfg. xml file is under the classpath (SRC folder) by default ).
I wrote a file to Parse Multiple hibernate files. cfg. XML file, access the hibernateutil class of multiple databases (this means that your project can use multiple databases, but I am not clear about the transaction management of multiple databases, ):
Code:
- Import org. hibernate. query;
- Import org. hibernate. Session;
- Import org. hibernate. sessionfactory;
- Import org. hibernate. cfg. configuration;
- Public final class hbnutil {// create a static sessionfactory according to hibernate. cfg. xml
- Private Static sessionfactory SF;
- Private Static sessionfactory mssf;
- Static {
- Try {
- Sf = new configuration (). Configure ("/hbn-sqlserver.cfg.xml ")
- . Buildsessionfactory ();
- Mssf = new configuration (). Configure ("/hbn-mysql.cfg.xml ")
- . Buildsessionfactory ();
- } Catch (exception e ){
- System. Err. println ("% error creating sessionfactory % ");
- E. printstacktrace ();
- }
- }
- Public static sessionfactory getsessionfactory (){
- Return SF;
- }
- Public static session getsession (){
- Session S = NULL;
- If (! SF. isclosed ())
- S = SF. opensession ();
- Return S;
- }
- Public static session getsessionbydb (string dbname) {// judge based on dbname
- Session S = NULL;
- If ("MySQL". Equals (dbname. tolowercase ())){
- If (! Mssf. isclosed ())
- S = mssf. opensession ();
- } Else if ("sqlserver". Equals (dbname. tolowercase ())){
- If (! SF. isclosed ())
- S = SF. opensession ();
- } Else {
- System. Out. println ("wrong dbname! ");
- }
- Return S;
- }
- Public static void closesessionfactory (){
- If (! SF. isclosed ()){
- SF. Close ();
- }
- }
- Public static void closesessionfactorybydb (string dbname ){
- If ("MySQL". Equals (dbname. tolowercase ())){
- If (! Mssf. isclosed ()){
- Mssf. Close ();
- }
- } Else if ("sqlserver". Equals (dbname. tolowercase ())){
- If (! SF. isclosed ()){
- SF. Close ();
- }
- } Else {
- System. Out. println ("wrong dbname! ");
- }
- }
- }