Hibernate how to build Org.hibernate.Session objects through configuration files and using sample source code

Source: Internet
Author: User
Tags sessions

Hibernate how to build Org.hibernate.Session objects from a configuration file
1, create org.hibernate.cfg.Configuration object configuration;

2, call the Configuration object's configure (path) method to load the configuration file, the parameter is hibernate core configuration file hibernate.cfg.xml location path;

3, the Buildsessionfactory () method of the configuration object loaded with the configuration file is invoked to obtain the Org.hibernate.SessonFactory object sessionfactory;

4, under normal circumstances call the Sessionfactory object Opensession () method to get Org.hibernate.Session object session (special cases, as shown in this example, through the Threadlocal management session, avoid frequent session creation and destruction);

—————— to this, the session is built successfully, with the following steps in use:

5. When it comes to transaction management, the BeginTransaction () method of the session is invoked to obtain the Org.hibernate.Transaction object transaction;

6, the specific database additions and deletions to check operations;

7. Conduct transaction management operations, such as submitting transaction transaction.commit ();

8, close session,session.close ();


Hibernatesessionfactory Class Code (with detailed comments):

<span style= "FONT-SIZE:14PX;"
>import org.hibernate.HibernateException;
Import org.hibernate.Session;

Import org.hibernate.cfg.Configuration; * * Hibernate the way to build Org.hibernate.Session objects through configuration files * 1, create org.hibernate.cfg.Configuration objects configuration; * 2, Call the Configuration object's configure (path) method to load the configuration file, which is the Hibernate core profile hibernate.cfg.xml location path; * 3, Invokes the Buildsessionfactory () method of the configuration object that loaded the configuration file to obtain the Org.hibernate.SessonFactory object sessionfactory; * 4, In general, the Opensession () method that invokes the Sessionfactory object obtains the Org.hibernate.Session object session (special cases, as shown in this example, are managed by the threadlocal session to avoid Sess <span style= "White-space:pre" > </span>ion frequent creation and destruction); * —————— to this, the session was built successfully, with the following steps in use: * 5, when it comes to transaction management, call SE Ssion's BeginTransaction () method obtains the Org.hibernate.Transaction object transaction; * 6, carries on the concrete database deletion to change the search operation; * 7, carries on the transaction management operation, If the transaction transaction.commit (); * 8, close session,session.close ();/public class Hibernatesessionfactory {//config file location (relative path) PRI					
	vate static String config_file_location = "/hibernate.cfg.xml"; Using thread-local variables treadlocal management sesSion, it provides each thread with a copy of the Session object//Can be combined with the filter to achieve the login status, combined with the listener to achieve session state changes and session value update private static final threadlocal<	
	session> threadLocal = new threadlocal<session> ();
	Used to load a configuration file private static Configuration Configuration = new Configuration ();
	Declare Hibernate session factory class object private static Org.hibernate.SessionFactory sessionfactory;
	private static String configfile = Config_file_location;	
			A static block that executes the static {try {//Load configuration file Configuration.configure (configfile) when the class loads;		
		Create Hibernate session Factory Object sessionfactory = Configuration.buildsessionfactory ();
			The catch (Exception e) {//Output error message System.err.println ("%%%% Error creating Sessionfactory%%%%");
		E.printstacktrace ();  The private Hibernatesessionfactory () {}//defines the method to get the session object (through Threadloacl) public static session getsession () throws	
		hibernateexception {//Gets the Session object session = (session) Threadlocal.get () of the current thread through the threadLocal get method; Judge Session Status if (session = NULL | |!session.isopen ()) {if (sessionfactory = null) {//Rebuild sessonfactory rebuildsessionfactory (); ///Get Session Object session = (Sessionfactory!= null) by Opensession method?
			Sessionfactory.opensession (): null;						
		The session will be referred to ThreadLocal management Threadlocal.set (session);
	return to session; }//Define Sessionfactory rebuild method public static void Rebuildsessionfactory () {try {//Reload configuration file Configuration.configur
			E (configfile);
		Create the Sessionfactory object again sessionfactory = Configuration.buildsessionfactory ();
			The catch (Exception e) {//Output error message System.err.println ("%%%% Error creating Sessionfactory%%%%");
		E.printstacktrace (); }//Defines the method of session shutdown public static void CloseSession () throws Hibernateexception {//The sess of the current thread through the threadlocal get method
		The Ion object Session Sessions = (session) Threadlocal.get ();
		ThreadLocal the empty threadlocal.set (null);
		if (session!= NULL) {//close session session.close (); }//get/set method public static Org.hibernate.SessionFactory GETsessionfactory () {return sessionfactory;
		The public static void Setconfigfile (String configfile) {hibernatesessionfactory.configfile = ConfigFile;
	Sessionfactory = null;
	public static Configuration GetConfiguration () {return Configuration; }}</span>


use methods at the DAO layer to student some of the actions of the table, as follows:

Import Java.util.Iterator;

Import java.util.List;
Import Org.hibernate.Query;
Import org.hibernate.Session;

Import org.hibernate.Transaction;
Import Com.sanqing.hibernate.HibernateSessionFactory;
Import com.sanqing.po.Student;

Import Com.sanqing.po.Subject;  public class Studentdaoimpl implements studentdao{public Student Findbystudentid (String StudentID) {Sessions session =
		Hibernatesessionfactory.getsession ();
		Student Student = (Student) session.get (Student.class, StudentID);
		Hibernatesessionfactory.closesession ();
	return student;
		public void Updatestudent (Student Student) {Sessions session = Hibernatesessionfactory.getsession ();
		Transaction Transaction = null;
			try{transaction = Session.begintransaction ();
			Session.update (student);
		Transaction.commit ();
			}catch (Exception ex) {ex.printstacktrace ();
		Transaction.rollback ();
	} hibernatesessionfactory.closesession (); Public list<student> findbystudentname (String studentname) {SessIon session = Hibernatesessionfactory.getsession ();
		Query query = Session.createquery ("From Student as Stu where stu.studentname =?");
		Query.setstring (0, Studentname);					
		List List = Query.list ();		
		Hibernatesessionfactory.closesession ();
	return list; List<student> Findbystudentclass (String Sclass) {Session session = Hibernatesessionfactory.getsession (
		);
		Query query = Session.createquery ("From Student as Stu where Stu.sclass =?");
		Query.setstring (0, Sclass);					
		List List = Query.list ();		
		Hibernatesessionfactory.closesession ();
	return list;
 }
}

If you want to learn more about the SSH framework, you can first see a demo: A typical SSH login and add a check demo detailed + source code

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.