vjame

          優(yōu)化代碼是無止境的
          隨筆 - 65, 文章 - 9, 評論 - 26, 引用 - 0
          數(shù)據(jù)加載中……

          Hibernate編程式事務(wù)


          采用編程式事務(wù)

          1、getCurrentSession()與openSession()的區(qū)別?
           * 采用getCurrentSession()創(chuàng)建的session會綁定到當(dāng)前線程中,而采用openSession()
             創(chuàng)建的session則不會
           * 采用getCurrentSession()創(chuàng)建的session在commit或rollback時會自動關(guān)閉,而采用openSession()
             創(chuàng)建的session必須手動關(guān)閉
            
          2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
           * 如果使用的是本地事務(wù)(jdbc事務(wù))
           <property name="hibernate.current_session_context_class">thread</property>
           * 如果使用的是全局事務(wù)(jta事務(wù))
           <property name="hibernate.current_session_context_class">jta</property>   

          1、創(chuàng)建包

          ├─client
          ├─manager
          │  └─impl
          ├─model
          └─util

          2、編寫po和hbm映射文件
          User.java

          package com.strongit.usermgr.model;

          public class User {
              
              
          private int id;
              
          private String name;
              
          public int getId() {
                  
          return id;
              }
              
          public void setId(int id) {
                  
          this.id = id;
              }
              
          public String getName() {
                  
          return name;
              }
              
          public void setName(String name) {
                  
          this.name = name;
              }

          }

          Log.java

          package com.strongit.usermgr.model;

          import java.util.Date;

          public class Log {
              
              
          private int id;
              
              
          private String type;
              
              
          private String detail;
              
              
          private Date time;

              
          public int getId() {
                  
          return id;
              }

              
          public void setId(int id) {
                  
          this.id = id;
              }

              
          public String getType() {
                  
          return type;
              }

              
          public void setType(String type) {
                  
          this.type = type;
              }

              
          public String getDetail() {
                  
          return detail;
              }

              
          public void setDetail(String detail) {
                  
          this.detail = detail;
              }

              
          public Date getTime() {
                  
          return time;
              }

              
          public void setTime(Date time) {
                  
          this.time = time;
              }

          }


          User.hbm.xml

          <?xml version="1.0"?>
          <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                             "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
          >
          <hibernate-mapping package="com.strongit.usermgr.model">
              
          <class name="User" table="t_user">
                  
          <id name="id">
                      
          <generator class="native" />
                  
          </id>
                  
          <property generated="never" lazy="false" name="name" />
              
          </class>
          </hibernate-mapping>

          Log.hbm.xml
          <?xml version="1.0"?>
          <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                             "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
          >
          <hibernate-mapping package="com.strongit.usermgr.model">
           
          <class name="Log" table="t_log">
            
          <id name="id">
             
          <generator class="native"/>
            
          </id>
            
          <property generated="never" lazy="false" name="type"/>
            
          <property generated="never" lazy="false" name="detail"/>
            
          <property generated="never" lazy="false" name="time"/>
           
          </class>
          </hibernate-mapping>

          3、配置hibernate.cfg.xml
          <!DOCTYPE hibernate-configuration PUBLIC
              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
              "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
          >

          <hibernate-configuration>
              
          <session-factory>
                  
          <property name="hibernate.connection.url">jdbc:mysql://localhost/spring_hibernate_1</property>
                  
          <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
                  
          <property name="hibernate.connection.username">root</property>
                  
          <property name="hibernate.connection.password">root</property>
                  
          <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
                  
          <property name="hibernate.show_sql">true</property>
                  
          <property name="hibernate.current_session_context_class">thread</property>
                  
          <!-- 
                  <property name="hibernate.current_session_context_class">jta</property>
                   
          -->        
                  
          <mapping resource="com/strongit/usermgr/model/User.hbm.xml"/>
                  
          <mapping resource="com/strongit/usermgr/model/Log.hbm.xml"/>
              
          </session-factory>
          </hibernate-configuration>

          4、創(chuàng)建數(shù)據(jù)庫

          啟動mysql      
          net start mysql

          執(zhí)行以下代碼
          package com.strongit.usermgr.util;

          import org.hibernate.cfg.Configuration;
          import org.hibernate.tool.hbm2ddl.SchemaExport;

          public class ExportDB {

              
          public static void main(String[] args) {
                  
          //讀取hibernate.cfg.xml文件
                  Configuration cfg = new Configuration().configure();
                  
                  SchemaExport export 
          = new SchemaExport(cfg);
                  
                  export.create(
          truetrue);

              }
          }

          5、編寫服務(wù)層代碼

          用戶接口 UserManager.java

          package com.strongit.usermgr.manager;

          import com.strongit.usermgr.model.User;

          public interface UserManager {
              
              
          public void addUser(User user);

          }

          用戶接口實現(xiàn) UserManagerImpl.java
          package com.strongit.usermgr.manager.impl;

          import java.util.Date;

          import org.hibernate.Session;

          import com.strongit.usermgr.manager.LogManager;
          import com.strongit.usermgr.manager.UserManager;
          import com.strongit.usermgr.model.Log;
          import com.strongit.usermgr.model.User;
          import com.strongit.usermgr.util.HibernateUtils;

          public class UserManagerImpl implements UserManager {

              
          public void addUser(User user) {
                  Session session 
          = null;
                  
          try {
          //            session = HibernateUtils.getSession();
                      session = HibernateUtils.getSessionFactory().getCurrentSession();
                      session.beginTransaction();
                      
                      session.save(user);

                      Log log 
          = new Log();
                      log.setType(
          "安全日志");
                      log.setDetail(
          "xxx進(jìn)入系統(tǒng)");
                      log.setTime(
          new Date());

                      LogManager logManager 
          = new LogManagerImpl();
                      logManager.addLog(log);

                      session.getTransaction().commit();
                  }
          catch(Exception e) {
                      e.printStackTrace();
                      session.getTransaction().rollback();
          //        }finally {
          //            HibernateUtils.closeSession(session);
                  }

              }

          }

          日志接口 LogManager.java
          package com.strongit.usermgr.manager;

          import com.strongit.usermgr.model.Log;

          public interface LogManager {
              
              
          public void addLog(Log log);

          }

          日志接口實現(xiàn) LogManagerImpl.java
          package com.strongit.usermgr.manager.impl;

          import com.strongit.usermgr.manager.LogManager;
          import com.strongit.usermgr.model.Log;
          import com.strongit.usermgr.util.HibernateUtils;

          public class LogManagerImpl implements LogManager {

              
          public void addLog(Log log) {
                  HibernateUtils.getSessionFactory().getCurrentSession().save(log);
              }

          }

          hibernate幫助類 HibernateUtils.java
          package com.strongit.usermgr.util;

          import org.hibernate.Session;
          import org.hibernate.SessionFactory;
          import org.hibernate.cfg.Configuration;

          public class HibernateUtils {

              
          private static SessionFactory factory;
              
              
          static {
                  
          try {
                      Configuration cfg 
          = new Configuration().configure();
                      factory 
          = cfg.buildSessionFactory();
                  }
          catch(Exception e) {
                      e.printStackTrace();
                  }
              }
              
              
          public static SessionFactory getSessionFactory() {
                  
          return factory;
              }
              
              
          public static Session getSession() {
                  
          return factory.openSession();
              }
              
              
          public static void closeSession(Session session) {
                  
          if (session != null) {
                      
          if (session.isOpen()) {
                          session.close();
                      }
                  }
              }
          }

          6、測試類
          package com.strongit.usermgr.client;

          import com.strongit.usermgr.manager.UserManager;
          import com.strongit.usermgr.manager.impl.UserManagerImpl;
          import com.strongit.usermgr.model.User;

          public class Client {

              
          /**  
               *   @Description 方法實現(xiàn)功能描述  
               *   
          @param args
               *   
          @author lanjh 9:02:58 PM
               *   
          @return void
               *   
          @throws  拋出異常說明
               
          */
              
          public static void main(String[] args) {

                  
                  User user 
          = new User();
                  user.setName(
          "lanjh");
                  
                  UserManager userManager 
          = new UserManagerImpl();
                  userManager.addUser(user);

              }

          }

          posted on 2009-08-07 18:02 lanjh 閱讀(627) 評論(0)  編輯  收藏 所屬分類: Java Web

          主站蜘蛛池模板: 兴义市| 岳阳县| 永宁县| 新津县| 江阴市| 仪征市| 东莞市| 洛隆县| 南郑县| 泸水县| 通城县| 增城市| 海林市| 鄂托克前旗| 左云县| 宝坻区| 郯城县| 穆棱市| 芦山县| 温州市| 梓潼县| 丹阳市| 潮安县| 石河子市| 高青县| 西充县| 武山县| 满洲里市| 堆龙德庆县| 汾西县| 壶关县| 石楼县| 涡阳县| 建宁县| 东港市| 布尔津县| 龙泉市| 桃园县| 云南省| 南澳县| 洮南市|