This article describes how to use hibernate to obtain Session instances in java. I hope this tutorial will be helpful to you.
Previously, SessionFactory sf = conf. buildSessionFactory () was recommended by the IDE not to continue using it. Now, the best way for hibernate to get the session is to use:
| The Code is as follows: |
Copy code |
|
Package org. Rudiment. hibernate;
Import org. Rudiment. hibernate. News;
Import org. hibernate. Session;
Import org. hibernate. SessionFactory;
Import org. hibernate. Transaction;
Import org. hibernate. cfg. Configuration;
Import org. hibernate. service. ServiceRegistry;
Import org. hibernate. service. ServiceRegistryBuilder;
Public class NewsManager
{
Public static void main (String [] args)
{
// Obtain the configuration
Configuration conf = new Configuration (). configure ();
// Obtain ServiceRegistry
ServiceRegistry sr = new ServiceRegistryBuilder ()
. ApplySettings (conf. getProperties ())
. BuildServiceRegistry ();
// Configure our SessionFactory
SessionFactory sf = conf. buildSessionFactory (sr );
// Obtain our Session
Session sess = sf. openSession ();
// Start our transaction
Transaction tx = sess. beginTransaction ();
News n = new News ();
N. setTitle ("ITkezhan ");
N. setContent ("IT Inn ");
// Save the Persistent Object
Sess. save (n );
// Submit the transaction
Tx. commit ();
// Close the Session
Sess. close ();
// Close SessionFactory
Sf. close ();
}
} |