posts - 29, comments - 0, trackbacks - 0, articles - 0
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          在ApplicationContext.xml 里面的配置:


          <!-- begin day -->

          <bean id="Initlogdatatarget" class="com.sotrip.statistic.scheduling.Initlogdata">
           <property name="tlogvisitDAO"><ref local="tlogvisitDAO"/></property>
           </bean>
          <bean id="Jobfortimerdaysservice"
               class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
           <property name="transactionManager"><ref local="transactionManager"/></property>
           <property name="target"><ref local="Initlogdatatarget"/></property>
           <property name="transactionAttributes">
            <props>  
             <prop key="exec*">PROPAGATION_REQUIRED</prop>
            </props>
           </property>
          </bean>

          <bean id="methodInvokingJobDetail"
           class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!--**** 此處的 targetObject 所指定的bean Jobfortimerdaysservice 需是service層的,通過它定義的事務屬性 就可以使得 targetMethod 所定義的方法具有事務屬性。-->
           <property name="targetObject"><ref bean="Jobfortimerdaysservice"/></property>
           <property name="targetMethod"><value>execute</value></property>
          </bean>

          <bean id="cronTrigger"
           class="org.springframework.scheduling.quartz.CronTriggerBean">
           <property name="jobDetail">
            <ref bean="methodInvokingJobDetail"/>
           </property>
           <property name="cronExpression">
            <value>0 0/2 * * * ?</value>
           </property>
          </bean>

          <!-- end day-->

          <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
           <property name="triggers">
            <list>
          <!--  <ref local="cronTriggertest"/>-->
             <ref local="cronTrigger"/>
              <ref local="cronTriggermonth"/><!-- 此處可以配置多個trigger-->
            </list>
           </property>
          </bean>

          在就是定時時間的定義:

          Cron-Expressions are used to configure instances of CronTrigger. Cron-Expressions are strings that are actually made up of seven sub-expressions, that describe individual details of the schedule. These sub-expression are separated with white-space, and represent:

          1. Seconds
          2. Minutes
          3. Hours
          4. Day-of-Month
          5. Month
          6. Day-of-Week
          7. Year (optional field)

          An example of a complete cron-expression is the string "0 0 12 ? * WED" - which means "every Wednesday at 12:00 pm".

          cronExpression配置說明

          字段   允許值   允許的特殊字符
            0-59   , - * /
            0-59   , - * /
          小時   0-23   , - * /
          日期   1-31   , - * ? / L W C
          月份   1-12 或者 JAN-DEC   , - * /
          星期   1-7 或者 SUN-SAT   , - * ? / L C #
          年(可選)   留空, 1970-2099   , - * /

           


          posted @ 2007-05-28 15:37 change| 編輯 收藏

          在spring里面我們一般是這樣來使用模板模式的:

          JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
          jdbcTemplate.update("UPDATE user SET age = 10 WHERE id = 'erica'");

          或者:

          JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
          jdbcTemplate
          .update(
          "UPDATE user SET age = ? WHERE id = ?",
          new PreparedStatementSetter() {
          public void setValues(PreparedStatementSetter ps)
          throws SQLException {
          ps.setInt(1, 18);
          ps.setString(2, "erica");
          }
          }
          );

          那么具體在spring里面他是怎么運作的呢?

          下面以query查詢為例:

          public class JdbcTemplate extends JdbcAccessor implements JdbcOperations, InitializingBean {

          。。。。。。。。。。。。。。。。。。。。。。。。。

          protected Object query(
             PreparedStatementCreator psc, final PreparedStatementSetter pss, final ResultSetExtractor rse)
             throws DataAccessException {
            if (logger.isDebugEnabled()) {
             String sql = getSql(psc);
             logger.debug("Executing SQL query" + (sql != null ? " [" + sql  + "]" : ""));
            }
            return execute(psc, new PreparedStatementCallback() {

          //此處以 PreparedStatementCallback 為參數調用 execute()方法,在execute()方法里面回調傳入的方法。在回調方法里面即根據傳入的 PreparedStatement 執行 查詢操作,返回結果。而 PreparedStatement  的獲取是在調用回調方法的客戶端實現即在execute()方法里面獲取,并作為參數傳給回調方法。
             public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
              ResultSet rs = null;
              try {
               if (pss != null) {
                pss.setValues(ps);
               }
               if (getFetchSize() > 0) {
                ps.setFetchSize(getFetchSize());
               }
               rs = ps.executeQuery();
               ResultSet rsToUse = rs;
               if (nativeJdbcExtractor != null) {
                rsToUse = nativeJdbcExtractor.getNativeResultSet(rs);
               }
               return rse.extractData(rsToUse);
              }
              finally {
               JdbcUtils.closeResultSet(rs);
               if (pss instanceof ParameterDisposer) {
                ((ParameterDisposer) pss).cleanupParameters();
               }
              }
             }
            });
           }

          那么在execue()方法里面是怎樣回調的呢?下面看看execue()方法:

          public Object execute(PreparedStatementCreator psc, PreparedStatementCallback action) {
            Connection con = DataSourceUtils.getConnection(getDataSource());
            PreparedStatement ps = null;
            try {
             Connection conToUse = con;
             if (this.nativeJdbcExtractor != null &&
               this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativePreparedStatements()) {
              conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
             }
             ps = psc.createPreparedStatement(conToUse);
             DataSourceUtils.applyTransactionTimeout(ps, getDataSource());
             PreparedStatement psToUse = ps;
             if (this.nativeJdbcExtractor != null) {
              psToUse = this.nativeJdbcExtractor.getNativePreparedStatement(ps);
             }
             Object result = action.doInPreparedStatement(psToUse);
             SQLWarning warning = ps.getWarnings();
             throwExceptionOnWarningIfNotIgnoringWarnings(warning);
             return result;
            }
            catch (SQLException ex) {
             throw getExceptionTranslator().translate(
               "executing PreparedStatementCallback [" + psc + "]", getSql(psc), ex);
            }
            finally {
             if (psc instanceof ParameterDisposer) {
              ((ParameterDisposer) psc).cleanupParameters();
             }
             JdbcUtils.closeStatement(ps);
             DataSourceUtils.closeConnectionIfNecessary(con, getDataSource());
            }
           }

          添加刪除的操作類似,只是他們的實現都在以execute命名的方法里面。

          public void execute(final String sql) throws DataAccessException {
            if (logger.isDebugEnabled()) {
             logger.debug("Executing SQL statement [" + sql + "]");
            }
            class ExecuteStatementCallback implements StatementCallback, SqlProvider {
             public Object doInStatement(Statement stmt) throws SQLException {
              stmt.execute(sql);
              return null;
             }
             public String getSql() {
              return sql;
             }
            }
            execute(new ExecuteStatementCallback());
           }

          public Object execute(final StatementCallback action) {
            Connection con = DataSourceUtils.getConnection(getDataSource());
            Statement stmt = null;
            try {
             Connection conToUse = con;
             if (this.nativeJdbcExtractor != null &&
               this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements()) {
              conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
             }
             stmt = conToUse.createStatement();
             DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
             Statement stmtToUse = stmt;
             if (this.nativeJdbcExtractor != null) {
              stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
             }
             Object result = action.doInStatement(stmtToUse);
             SQLWarning warning = stmt.getWarnings();
             throwExceptionOnWarningIfNotIgnoringWarnings(warning);
             return result;
            }
            catch (SQLException ex) {
             throw getExceptionTranslator().translate("executing StatementCallback", getSql(action), ex);
            }
            finally {

          //這里就是我們自己寫程序的時候需要寫的關于數據庫鏈接的關閉操作
             JdbcUtils.closeStatement(stmt);
             DataSourceUtils.closeConnectionIfNecessary(con, getDataSource());
            }
           }

          posted @ 2007-05-28 15:34 change| 編輯 收藏

          Spring 的聲明式事務是通過TransactionProxyFactoryBean 來實現的,而它是通過持有一個攔截器:TransactionInterceptor 來做到的。

          public class TransactionProxyFactoryBean extends ProxyConfig implements FactoryBean, InitializingBean {

           private final TransactionInterceptor transactionInterceptor = new TransactionInterceptor();

           /**
            * Set the transaction manager. This will perform actual
            * transaction management: This class is just a way of invoking it.
            * @see TransactionInterceptor#setTransactionManager
            */
           public void setTransactionManager(PlatformTransactionManager transactionManager) {
            this.transactionInterceptor.setTransactionManager( transactionManager);
           }

          。。。。。。。。。。//聲明的事務屬性在這里得到                                   

                                                 //見(DefaultTransactionDefinition)定義

          }

          //TransactionInterceptor 在service層的方法調用的時候,會更具配置判斷調用的方法//是否需要事務的處理,若需要則獲取設置事務屬性對象和事務管理器并啟動一個//事務,而其具體的實現是委托給 TransactionAspectSupport 類的//createTransactionIfNecessary 方法實現的,其類結構如下

          public class TransactionInterceptor extends TransactionAspectSupport implements MethodInterceptor {

           public Object invoke(MethodInvocation invocation) throws Throwable {
            // Work out the target class: may be null.
            // The TransactionAttributeSource should be passed the target class
            // as well as the method, which may be from an interface
            Class targetClass = (invocation.getThis() != null) ? invocation.getThis().getClass() : null;
            
            // Create transaction if necessary
            TransactionInfo txInfo = createTransactionIfNecessary(invocation.getMethod(), targetClass);//此處即是根據配置的聲明性事務屬性決定方法事務級別

            Object retVal = null;
            try {
             // This is an around advice.
             // Invoke the next interceptor in the chain.
             // This will normally result in a target object being invoked.
             retVal = invocation.proceed();
            }
            catch (Throwable ex) {
             // target invocation exception
             doCloseTransactionAfterThrowing(txInfo, ex);
             throw ex;
            }
            finally {
             doFinally(txInfo);
            }
            doCommitTransactionAfterReturning(txInfo);

            return retVal;
           }
           
          }

          //在TransactionAspectSupport 類方法createTransactionIfNecessary()里面根據配置的聲明性事務屬性,決定啟動一個事務,和返回事務級別(信息):

          protected TransactionInfo createTransactionIfNecessary(Method method, Class targetClass) {
            // If the transaction attribute is null, the method is non-transactional
            TransactionAttribute transAtt = this.transactionAttributeSource.getTransactionAttribute(method, targetClass);
            TransactionInfo txInfo = new TransactionInfo(transAtt, method);
            if (transAtt != null) {
             // We need a transaction for this method
             if (logger.isDebugEnabled()) {
              logger.debug("Getting transaction for " + txInfo.joinpointIdentification());
             }

             // The transaction manager will flag an error if an incompatible tx already exists

             txInfo.newTransactionStatus(this.transactionManager.getTransaction(transAtt));

          //此處的參數 this.transactionManager.getTransaction(transAtt) 即是調用各具體平臺的 transactionManager 來獲取她的事務屬性,在獲取事務屬性的同時她會更具具體的事務屬性 來決定是否開始和怎么開始一個事務;見類AbstractPlatformTransactionManager  結構。

           public abstract class AbstractPlatformTransactionManager implements PlatformTransactionManager, Serializable {

          。。。。。。。。。。。。。。。。。。。。。

          public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {

          if (isExistingTransaction(transaction)) {

          //下面即是 更具具體的配置事務屬性 來決定事務
             if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER)
          {
              throw new IllegalTransactionStateException(
                "Transaction propagation 'never' but existing transaction found");
             }
             if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
              if (debugEnabled) {
               logger.debug("Suspending current transaction");
              }
              Object suspendedResources = suspend(transaction);
              boolean newSynchronization = (this.transactionSynchronization == SYNCHRONIZATION_ALWAYS);
              return newTransactionStatus(
                null, false, newSynchronization, definition.isReadOnly(), debugEnabled, suspendedResources);
             }
             else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
              if (debugEnabled) {
               logger.debug("Creating new transaction, suspending current one");
              }
              Object suspendedResources = suspend(transaction);

          //此處的doBegin 方法給更具具體的平臺和配置事務屬性來啟動一個事務
              doBegin(transaction, definition);
              boolean newSynchronization = (this.transactionSynchronization != SYNCHRONIZATION_NEVER);
              return newTransactionStatus(
                transaction, true, newSynchronization, definition.isReadOnly(), debugEnabled, suspendedResources);
             }

          。。。。。。。。。。。。。。。。。。。。。

          }

            // We always bind the TransactionInfo to the thread, even if
            // we didn't create a new transaction here.
            // This guarantees that the TransactionInfo stack will be
            // managed correctly even if no transaction was created by
            // this aspect.
            txInfo.bindToThread();
            return txInfo;
           }

          //下面是事務的提交操作,回滾類似

          protected void doCommitTransactionAfterReturning(TransactionInfo txInfo) {
            if (txInfo != null && txInfo.hasTransaction()) {
             if (logger.isDebugEnabled()) {
              logger.debug("Invoking commit for transaction on " + txInfo.joinpointIdentification());
             }

            //這里的transactionManager 就是Spring配置文件里面配置的事務 如:org.springframework.orm.hibernate3.HibernateTransactionManager 。
             this.transactionManager.commit(txInfo.getTransactionStatus());

            }
           }

          //

          protected void doFinally(TransactionInfo txInfo) {
            if (txInfo != null) {
             txInfo.restoreThreadLocalStatus();
            }
           }
          private void restoreThreadLocalStatus() {
             // Use stack to restore old transaction TransactionInfo.
             // Will be null if none was set.
             currentTransactionInfo.set(oldTransactionInfo);
            }

          //下面以 HibernateTransactionManager  例,說說事務的開始和提交/回滾

          //此dobegin()方法即是開始一個事務
           protected void doBegin(Object transaction, TransactionDefinition definition) {
            HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

            if (txObject.getSessionHolder() == null) {
             Session session = SessionFactoryUtils.getSession(
               getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator(), false);
             if (logger.isDebugEnabled()) {
              logger.debug("Opened new session [" + session + "] for Hibernate transaction");
             }
             txObject.setSessionHolder(new SessionHolder(session), true);
            }

            txObject.getSessionHolder().setSynchronizedWithTransaction(true);
            Session session = txObject.getSessionHolder().getSession();

            try {
             Connection con = session.connection();
             Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
             txObject.setPreviousIsolationLevel(previousIsolationLevel);

             if (definition.isReadOnly() && txObject.isNewSessionHolder()) {
              // just set to NEVER in case of a new Session for this transaction
              session.setFlushMode(FlushMode.NEVER);
             }

             if (!definition.isReadOnly() && !txObject.isNewSessionHolder()) {
              // we need AUTO or COMMIT for a non-read-only transaction
              FlushMode flushMode = session.getFlushMode();
              if (FlushMode.NEVER.equals(flushMode)) {
               session.setFlushMode(FlushMode.AUTO);
               txObject.getSessionHolder().setPreviousFlushMode(flushMode);
              }
             }

             // add the Hibernate transaction to the session holder

          //此處即是真正的調用了hibernate的session開始一個事務session.beginTransaction() 。
             txObject.getSessionHolder().setTransaction(session.beginTransaction());

             // register transaction timeout
             if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
              txObject.getSessionHolder().setTimeoutInSeconds(definition.getTimeout());
             }

             // register the Hibernate Session's JDBC Connection for the DataSource, if set
             if (getDataSource() != null) {
              ConnectionHolder conHolder = new ConnectionHolder(con);
              if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
               conHolder.setTimeoutInSeconds(definition.getTimeout());
              }
              if (logger.isDebugEnabled()) {
               logger.debug("Exposing Hibernate transaction as JDBC transaction [" +
                 conHolder.getConnection() + "]");
              }
              TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);
              txObject.setConnectionHolder(conHolder);
             }

             // bind the session holder to the thread
             if (txObject.isNewSessionHolder()) {
              TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder());
             }
            }

            catch (Exception ex) {
             SessionFactoryUtils.closeSessionIfNecessary(session, getSessionFactory());
             throw new CannotCreateTransactionException("Could not create Hibernate transaction", ex);
            }
           }

          //回滾

          protected void doCommit(DefaultTransactionStatus status) {
            HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction();

          。。。。。。。。。。。。。。。。。。。。。。。。。。
            try {
             txObject.getSessionHolder().getTransaction().commit();
            }
            catch (net.sf.hibernate.TransactionException ex) {
             // assumably from commit call to the underlying JDBC connection
             throw new TransactionSystemException("Could not commit Hibernate transaction", ex);
            }
            catch (JDBCException ex) {
             // assumably failed to flush changes to database
             throw convertJdbcAccessException(ex.getSQLException());
            }
            catch (HibernateException ex) {
             // assumably failed to flush changes to database
             throw convertHibernateAccessException(ex);
            }
           }

            }
            else {
             // The TransactionInfo.hasTransaction() method will return
             // false. We created it only to preserve the integrity of
             // the ThreadLocal stack maintained in this class.
             if (logger.isDebugEnabled())
              logger.debug("Don't need to create transaction for " + methodIdentification(method) +
                ": this method isn't transactional");
            }

          posted @ 2007-05-28 15:33 change| 編輯 收藏

          引用:http://shidu.blogbus.com/logs/2004/12/540365.html

          配置文件大概如下:
          <action-mappings>
          <action path="/account"
          name="accountForm"
          parameter="action"
          scope="request"
          type="com.ai.uaap.admin.web.action.AccountAction">
          <forward name="listOK" path="/AccountMaster.jsp" />
          <forward name="removeOK" path="/account.do?action=list" redirect="true" />
          </action>

          我在執行完remove的方法之后的代碼是return mapping.findForward("removeOK")。這時就會訪問account.do?action=list這個地址,以前我想在account.do?action=list之后繼續添加參數(例如account.do?action=list&abc=123)不知道該怎么實現。

          今天看到一個資料給出了實現:
          String path = mapping.findForward("removeOK").getPath();
          ActionForward forward = new ActionForward(path + "&abc=123", true);
          //這里的true是Redirect
          return forward;

          posted @ 2007-05-28 15:32 change| 編輯 收藏

          CREATE TABLE V_GIS_MONTH
          (
            ID         VARCHAR2(255 BYTE)                 NOT NULL,
            VISITTIME  DATE                               DEFAULT NULL,
            GISNAME    VARCHAR2(255 BYTE),
            GISLEVEL   VARCHAR2(255 BYTE),
            PARENT     VARCHAR2(255 BYTE),
            VNUMBER    NUMBER(19),
            IPFROM     VARCHAR2(255 BYTE),
            IPLEVEL    VARCHAR2(2 BYTE),
            GISPATH    VARCHAR2(1024 BYTE)
          )
          TABLESPACE USERS

          PCTUSED    0
          PCTFREE    10
          INITRANS   1
          MAXTRANS   255
          STORAGE    (
                      INITIAL          64K
                      MINEXTENTS       1
                      MAXEXTENTS       2147483645
                      PCTINCREASE      0
                      BUFFER_POOL      DEFAULT
                     )
          LOGGING
          NOCACHE
          NOPARALLEL;


          ALTER TABLE V_GIS_MONTH ADD (
            PRIMARY KEY (ID)
              USING INDEX
              TABLESPACE USERS
              PCTFREE    10
              INITRANS   2
              MAXTRANS   255
              STORAGE    (
                          INITIAL          64K
                          MINEXTENTS       1
                          MAXEXTENTS       2147483645
                          PCTINCREASE      0
                         ));


          select gisdays.ipfrom,gisdays.gisname,sum(gisdays.vnumber)AS count from V_Gis_Month gisdays where gisdays.GISPATH = '/sotrip_dest/destination_home/china/zhejiang/' and gisdays.iplevel='3' group by gisdays.ipfrom,gisdays.gisname ORDER BY count desc;

          gis:表示目的地

          在數據庫里面這樣的查詢是可以的,但是用這樣的語句在hibernate的DAO層

          這樣做:

          String queryString = "select gisdays.ipfrom,sum(gisdays.vnumber) AS count  from "+strtable+" gisdays where gisdays.iplevel='"+striplevel+"' "+strquery+" and to_char(gisdays.visittime,'YYYY-MM-DD')  between '"+strfrom+"' and '"+strto+"' group by gisdays.ipfrom ORDER BY count desc";           
            

          Iterator iterator = this.getHibernateTemplate().find(queryString).iterator();

          是不行的,會出現異常,報錯。

          改為:

          String queryString = "select gisdays.ipfrom,sum(gisdays.vnumber)  from "+strtable+" gisdays where gisdays.iplevel='"+striplevel+"' "+strquery+" and to_char(gisdays.visittime,'YYYY-MM-DD')  between '"+strfrom+"' and '"+strto+"' group by gisdays.ipfrom ORDER BY sum(gisdays.vnumber) desc";           

           Iterator iterator = this.getHibernateTemplate().find(queryString).iterator();

          while(iterator.hasNext())
            {
             Object[] pair = (Object[])iterator.next();   
             VGisMonth gismonth = new VGisMonth();
             for(int i=0;i<pair.length;i++)
             {
              System.out.println("pair["+i+"]="+pair[i]);
             }

          }//這里iterator 所返回的是對象數組,它把取得的每一列都作為一個對象,然后返回一個對象數組的疊代器,然后我們就可以取出里面的每一列(對象)轉換成相應的數據類型,(這里 strtable 是table所對應的實體的名字)

          就可以了。應該是在里面不支持對  統計添加的列 的別名命名吧。呵呵:)

          posted @ 2007-05-28 15:31 change| 編輯 收藏

                本命年已經悄然過去,在這一年里面確實有太多的心酸淚史。雖然沒有招受太多肉體上的傷害,但是生心的痛苦遠勝于此。

                 過去的日子總感覺自己活的渾渾噩噩的。生活,學習,感情,都是一團糟。然而在這段暈呼的歲月里面卻有一件事情總是不間斷,那就是思索生活的意義。”活著是為了什么“,“。。。”諸如此類的莫名其妙的為什么還有很多很多,我想我都快可以自己在寫一本十萬個為什么了。說句老實話,本人沒有為了人類的從高理想而活的高尚情操,所以這種思索只會讓我變得更加的頹廢,萎縮。我想不清楚這么高深的問題。也許是太富有哲理性了,更本就不是我這種凡夫俗子所能夠想的通的。對于這種問題的思索讓我失去了方向,干什么事情都找不著北。也因此帶來了很多的困擾,也因此而承受了很多原本就不應該承受的負擔。太多的思緒,太多的顧慮,太多的想不通,太多,太多,太多的問題使我的腦袋都已經在塞不下任何其他的東西。

                在這一年里面,我們去了索創的培訓,這確實是一個不錯的機會,然而心不在焉的也沒有把心思花在上面,一連串的心事讓我身在教室心在外。雖是基本不間斷的去上課,可我能夠感覺的到,我像是一具形尸走肉,盲目的穿行在紛亂的人群里面。感覺自己真的使那么的孤單,那么的無助。慢慢的自己也就開始喜歡上了幻想,喜歡活在自己的夢里面。

                 在后來就進了公司去實習,這也許就是一個戰時的避難所,然而它并沒有使我得到多少解脫,我還是依然活在我的夢里面。我希望通過不間歇的勞作使自己盡量的不要理會那些身外之事,然而我畢竟還沒有去少林出家,自然少不了七情六欲,固然沒有煉得真身,依然為塵世所繞。也許活在自己的夢里面是幸福的,夢真的醒來也是幸福的,但是我卻處在了陰陽交界似睡非省的邊緣。糊里糊涂的活著,活在稀里糊涂的世界里面。。。

                 有人說失敗的男人才會想家。看來我真的是一個失敗的男人,因為今年的我就特別的想回家。也許我真的是需要在家里調養一下,忘卻我心中的那份不應有的牽掛。

          posted @ 2007-05-28 15:31 change| 編輯 收藏

          相信大家對于mvc模式并不陌生,它的主要作用就是使 :結果展示,業務操作,以及后臺的數據庫操作,

          起到隔離的效果,這種分層解偶 的思想最大的好處應該就是便于擴展吧。對于現在比較流行的網站建設架構

          structs+hibernate+spring來說,就是用struct的標簽來做結果的展示,用它的action來處理業務邏輯,而用

          hibernate來處理業務邏輯所要操作的后臺數據庫數據。而他們各自的擴展變化和具體操作實現的變化 基本上

          都不合影響到其他層的改動。個人感覺   數據庫的設計定了,那么更具業務需求的hibernate接口成基本上就是

          定下來了,因為數據庫的操作無非不是根據 不同的條件實現  增,刪,改,查!說穿也就是說hibernate所做的

          只是對于你所設計的表 做 增,刪,改,查 操作,而這些操作基本上是固定模式。對于spring的用處主要就是

          用它的課配置事務處理的能力。

          posted @ 2007-05-28 15:29 change| 編輯 收藏

          最近用structs+hibernate+spring做的一個項目,后臺用的是oracle92。

          測試的時候發現了一個數據的插入問題,在數據庫里面定義的一個varchar(4000)的字段,在action層打印顯示的字段大小明明就是<4000字節的  可是一執行用hibernate插入操作的時候,就報錯,而且顯示的字段大小只要一超過2000就報錯說超出范圍,而且漢字還是3字節編碼的,而所有的頁面都用gbk編碼郭了,一直百思不得其解,原來是oracle驅動得問題。oracle92自己帶的驅動只是適合jdk1.3以前的,在oracle的官方網站上下載一個最新驅動,一切ok!暈吧!呵呵,希望大家  不要范和我一樣的毛病。為此二郁悶。

          posted @ 2007-05-28 15:28 change 閱讀(133) | 評論 (0)編輯 收藏

          比如在刪除一條在數據庫操作的時候 我們一般是類似是這樣使用:

          this.getHibernateTemplate().delete("from Information where INFOID='"+infoid.trim()+"'");

          然而具體在spring內部是怎么操作的呢?

          delete()----->excecute()----->執行回調方法HibernateCallback .doInHibernate()。

          下面來讓我們來直接看一下spring的源代碼。

          //hibernate回調接口

          public interface HibernateCallback {

          Object doInHibernate(Session session) throws HibernateException, SQLException;

          }

          //

          package org.springframework.orm.hibernate;

          public class HibernateTemplate extends HibernateAccessor implements HibernateOperations {

          //。。。。。。。。。。。。。。。。

          public int delete(final String queryString) throws DataAccessException {
            Integer deleteCount = (Integer) execute(new HibernateCallback() {//定義回調實現
             public Object doInHibernate(Session session) throws HibernateException {
              checkWriteOperationAllowed(session);
              return new Integer(session.delete(queryString));//此處有hibernate的實現操作
             }
            });
            return deleteCount.intValue();
           }

           public Object execute(HibernateCallback action) throws DataAccessException {
            Session session = (!isAllowCreate() ? SessionFactoryUtils.getSession(getSessionFactory(), false) :
            SessionFactoryUtils.getSession(getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator()));
            boolean existingTransaction = TransactionSynchronizationManager.hasResource(getSessionFactory());
            if (!existingTransaction && getFlushMode() == FLUSH_NEVER) {
             session.setFlushMode(FlushMode.NEVER);
            }
            try {
             Object result = action.doInHibernate(session);//此處調用hibernatecallback回調接口即hibernate的實現
             flushIfNecessary(session, existingTransaction);
             return result;
            }
            catch (HibernateException ex) {
             throw convertHibernateAccessException(ex);
            }
            catch (SQLException ex) {
             throw convertJdbcAccessException(ex);
            }
            catch (RuntimeException ex) {
             // callback code threw application exception
             throw ex;
            }
            finally {
             SessionFactoryUtils.closeSessionIfNecessary(session, getSessionFactory());
            }
           }

          //。。。。。。。。。。。。。。

          //其他操作類似

          }


          posted @ 2007-05-28 15:27 change| 編輯 收藏

          僅列出標題
          共3頁: 上一頁 1 2 3 
          主站蜘蛛池模板: 台湾省| 纳雍县| 图木舒克市| 中宁县| 南投市| 仁怀市| 兖州市| 长乐市| 锡林浩特市| 宁晋县| 烟台市| 雅江县| 五大连池市| 肥乡县| 图木舒克市| 河北省| 泌阳县| 孝感市| 东山县| 海盐县| 乌审旗| 建阳市| 集贤县| 彩票| 民乐县| 黎平县| 南木林县| 儋州市| 乌拉特前旗| 新河县| 宁陵县| 商丘市| 隆林| 宁德市| 会泽县| 隆化县| 万年县| 安多县| 五台县| 崇明县| 连城县|