Steps for using hibernate4 for data persistence
To use hibernate for Data Persistence:
1. Write persistence class: POJO + ing File
2. Get the Configuration object
Configuration is mainly used to manage the Configuration information of hibernate and read the content in hibernate. cfg. xml. You can configure the basic information for connecting to the database and determine its corresponding ing file (*. hbm. xml)
It is worth noting that we usually put the hibernate. cfg. xml file under the classpath file path, that is, under the src folder.
Configuration supports two methods:
① Property file (hibernate. properties)
Configuration configuration = new Configuration ();
② Xml file (hibernate. cfg. xml)
Configuration configuration = new Configuration (). configure ();
3. Get the sessionFactory object
SessionFactory is very resource-consuming. Generally, an application creates only one sessionFactory object.
It is worth noting that the method of creating hibernate4 is a little different from that before hibernate4.
4. Get the session object and then open the transaction
5. operate databases in an object-oriented manner
6. Close transactions and close sessions
The specific implementation reference code is as follows:
@ Testpublic void test () {// 1. create a SessionFactory object SessionFactory sessionFactory = null; // 1 ). create a Configuration object: corresponds to the basic Configuration information of hibernate and the object relationship ing information configuration Configuration = new Configuration (). before configure (); // 4.0, create // sessionFactory = configuration. buildSessionFactory (); // 2 ). create a ServiceRegistry object: the newly added object of hibernate 4.x // any configuration and service of hibernate must be registered in this object before it becomes effective. serviceRegistry serviceRegistry = new ServiceRegistryBuilder (). applySettings (configuration. getProperties ()). buildServiceRegistry (); // 3 ). sessionFactory = configuration. buildSessionFactory (serviceRegistry); // 2. create a Session object Session = sessionFactory. openSession (); // 3. enable Transaction transaction Transaction = session. beginTransaction (); // 4. run the save operation News news = new News ("Java12345", "ATGUIGU", new Date (new java. util. date (). getTime (); session. save (news); // 5. commit transaction. commit (); // 6. disable Sessionsession. close (); // 7. disable SessionFactory object sessionFactory. close ();}