The discussion on how to manage sessions is much more discussion on how to manage session, but because there is no complete Run's example, many people are still confused at this point. Today, I posted a small example of myself, I hope to save the learning time of later people. This example is implemented: 1. Manage Session with Threadlocal, guarantees the same session (connection) in a thread 2. In ServletFilter, INITESessionFactory and CloseSession, guaranteed that there is only one sessionFactory in one app and achieve session-per-request, INSTEAD OF SESSION-Per-Operation 3. The roughness of DAO can first refer to the first example written by I, Tomcat MySQL UltraEdit, 10 minutes Hibernate first experience http://forum.javaeye.com/Viewtopic. PHP? T = 4077 1. Guaranteed your MySQL work normally.
Java code:
Create Table Cat (20) Not NULL, NAME VARCHAR (20) Not Null, Sex Char (1), Weight Float, Primary Key (Cat_ID)); Insert Cat Values ('1', 'Ada', 'F ', 5); INSERT CAT VALUES (' 2 ',' Belinda ',' F ', 10);
2. Make sure your Tomcat works fine. Then Stop Tomcat. Add: {Tomcat_home} /conf/server.xml:
Java code:
Java code: // sessionFactory is a singleton private static SessionFactory sessionFactory; // init is called public static void init in filter.init () in () throws HibernateException // currentSession been invoked public static Session currentSession DAO in () throws HibernateException // closeSession Public static void closesession () THROWS HIBERNATEXCEPTION in FILTER.DOFILTER () CatdaoImpl Java code: // Note: The session here is not clos, while only flush public void delcat (string stratid) {Try {session s = hibernatesisFactory.currentSession (); Object cat = s.load (cat.class, strcatid) S.delete (CAT); sflush ();} catch (hibernateException e) {E.PrintStackTrace ();}} Catdao Java code: // Package of CAT's CRUD Public Interface Catdao {Public Void Creat Cat (Cat); Public Void Updatecat (Cat Cat); Public Void Delcat (String Strcatid);} This is just the most for Dao A rough package, there is also a layer of DAOFActory in practical applications. About DAO Pattern, you can get more information here: http: //java.sun.com/boeprints/corej2eepartnerns/patterns/dataaccessObject.html PS: Del method To determine if it is to determine which Object does not exist. otherwise...........