How to Use hibernate to obtain Session instances in java

Source: Internet
Author: User

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 ();
}
}

 

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.