JAva Oracleストアド・プロシージャの操作、およびExcelレポートの生成


リード
   エンタープライズ・アプリケーション・システムでは、レポートの生成を要求することがよくあります.
   当社がこれまでレポートを生成してきたタスクは、データベース・グループに任せられています.
   あいにく、新しいプロジェクトのオンラインでは、ブラウザの下に表示されるレポートを完了するように要求されています.
   私はレポートツールをあまり使いません.複雑なレポートではありません.要求通りにデータをつかむだけです.
   HTMLまたはExcelで表示
  
  
シナリオ:
   タイミングトリガSpringに付属のquartz
   Oracleストアド・プロシージャは、取得するデータを実行します.
   POIをレポート形式で表示
目的:
   開発手記として、仕事の経験を積む
   まずデータ生成から、私がつかむデータは新しいテーブルで保存します.
   コードがたくさん貼られるかもしれません
  

create or replace procedure outcall_report_pro
(
 /*         */
 --PREFIX_YMD IN VARCHAR2, --          2009-06-25
 /*         */
 --POSTPOSITION_YMD IN VARCHAR2
 /*     */
 INPUT_YMD IN VARCHAR2 --         
 /*    */
)

is
     w_RESULT  NUMBER;
           
     /*             */
    CURSOR cur_read_result
    
    IS
       SELECT
               MAINTABLE.cscalltime
             , MAINTABLE.cscallresult
             , MAINTABLE.cscallrtcause
             , MAINTABLE.csoperatorid
             , MAINTABLE.userid
             , MAINTABLE.ascalltime
             , MAINTABLE.ascallresult
             , MAINTABLE.ascallrtcause
             , MAINTABLE.asoperatorid
             , MAINTABLE.orderid
             , ASALLOT.asallotat
             , CSALLOT.csallotat
       FROM
            (
              select 
                       cstable.calltime as cscalltime
                     , cstable.callresult as cscallresult 
                     , cstable.callrtcause as cscallrtcause
                     , cstable.operatorid as csoperatorid 
                     , cstable.userid
                     , astable.calltime as ascalltime 
                     , astable.callresult as ascallresult 
                     , astable.callrtcause as ascallrtcause 
                     , astable.operatorid as asoperatorid
                     , astable.orderid
              from (
                     select 
                              cst.calltime 
                            , cst.callresult
                            , cst.callrtcause 
                            , cst.operatorid
                            , cst.userid
                            , cst.orderid
                     from 
                            erp2_usercommunicate_log cst 
                     where 
                               cst.callway = 1 
                           and cst.callobject = 1 
                           and to_char(cst.calltime,'yyyy-MM-dd')=INPUT_YMD 
                           order by cst.calltime desc
              ) cstable, 
                  (         
                    select 
                             cst.calltime
                           , cst.callresult 
                           , cst.callrtcause 
                           , cst.operatorid 
                           , cst.userid
                           , cst.orderid
                    from 
                           erp2_usercommunicate_log cst
                    where 
                          (orderid,calltime) 
                          in  
                              ( 
                                select orderid,max(calltime)
                                from 
                                     erp2_usercommunicate_log cst 
                                     where 
                                               cst.callway = 1 
                                           and cst.callobject = 2 
                                           and to_char(cst.calltime,'yyyy-MM-dd')=INPUT_YMD 
                                           group by orderid
                                        )                
                               ) astable 
                 where
                       cstable.orderid = astable.orderid(+)
            ) MAINTABLE,
            (
               select 
                        allot.allottime as asallotat
                      , allot.userid as asuserid
               from erp2_userallot_log allot
               where 
                     (userid, allottime) in 
                     (
                       select userid, min(allottime) 
                       from erp2_userallot_log  
                       where     state=2 
                             and to_char(allottime,'yyyy-MM-dd')=INPUT_YMD 
                             group by userid
                     )
            ) ASALLOT,
            (
              select 
                       allot.allottime as csallotat
                     , allot.userid as csuserid
              from erp2_userallot_log allot
              where 
                    (userid, allottime) in 
                    (
                      select userid, min(allottime) 
                      from erp2_userallot_log  
                      where     state=1
                            and to_char(allottime,'yyyy-MM-dd')=INPUT_YMD
                            group by userid
                    )
            ) CSALLOT
            where 
                     MAINTABLE.userid = ASALLOT.asuserid(+)
                and  MAINTABLE.userid = CSALLOT.csuserid(+)
       ;
       
       

    /*        */
    FUNCTION fnc_record --   0  ,   -1
    (
                p_csallotat IN DATE    
             ,  p_cscalltime IN DATE
             ,  p_cscallresult IN NUMBER
             ,  p_cscallresultcause IN VARCHAR2
             ,  p_asallotat IN DATE
             ,  p_ascalltime IN DATE
             ,  p_ascallresult IN NUMBER
             ,  p_ascallresultcause IN VARCHAR2
             ,  p_userid IN NUMBER
             ,  p_asoperatorid IN NUMBER
             ,  p_csoperatorid IN NUMBER
             ,  p_orderid IN NUMBER
             
    ) RETURN NUMBER
    IS
      BEGIN
      
      INSERT INTO
             ERP2_OUTCALL_REPORT
      (
                ID
             ,  REPORTAT
             ,  CSALLOTAT
             ,  CSCALLAT
             ,  CSCALLRESULT
             ,  CSCALLRESULTCAUSE
             ,  ASCALLAT
             ,  ASCALLRESULT
             ,  ASCALLRESULTCAUSE
             ,  ASALLOTAT
             ,  USERID
             ,  ASID
             ,  CSID
             ,  ORDERID
      )
      values 
      (
                seq_erp2_outcall_report_id.nextval
             ,  sysdate
             ,  p_csallotat
             ,  p_cscalltime
             ,  p_cscallresult
             ,  p_cscallresultcause
             ,  p_ascalltime
             ,  p_ascallresult
             ,  p_ascallresultcause
             ,  p_asallotat
             ,  p_userid
             ,  p_asoperatorid
             ,  p_csoperatorid
             ,  p_orderid
      );
      
      RETURN 0;
      EXCEPTION
          WHEN OTHERS THEN
      RETURN -1;
    END fnc_record;
       
    
    /*    */
    FUNCTION fnc_excute 
    RETURN NUMBER
    IS
      w_RES       NUMBER := 0; 
      
      BEGIN
      IF w_RES = 0 THEN
            FOR rec IN cur_read_result
             LOOP
                w_RES := fnc_record(rec.csallotat
                        , rec.cscalltime
                        , rec.cscallresult
                        , rec.cscallrtcause
                        , rec.asallotat
                        , rec.ascalltime
                        , rec.ascallresult
                        , rec.ascallrtcause
                        , rec.userid
                        , rec.asoperatorid
                        , rec.csoperatorid
                        , rec.orderid);
                         
              EXIT WHEN w_RES != 0;
              END LOOP;
      END IF;
      
      RETURN w_RES;
      EXCEPTION
          WHEN OTHERS THEN
      RETURN -1;
      
    END fnc_excute;
    
begin
     
     w_RESULT := 0;   
         IF w_RESULT = 0 THEN  
            w_RESULT := fnc_excute;   
         END IF;   
            
         IF w_RESULT != 0 THEN  
                ROLLBACK;     
         END IF;   
        
     EXCEPTION   
        WHEN OTHERS THEN  
            ROLLBACK;
   
end outcall_report_pro;

   

   次にsshアーキテクチャの下で呼び出しストレージプロセスを実行します(使用していないものはよく見てください)
  


/**
 * 
 * @version     :2009-6-25    :    -        
 *
 */
@SuppressWarnings({"serial","unused","unchecked"})
public class OutCallReportManageImpl {
	/*
	 *     
	 */
	Log log = LogFactory.getLog(OutCallReportManageImpl.class);
	
	private StatisticsDao statisticsdao;

	public StatisticsDao getStatisticsdao() {
		return statisticsdao;
	}
	
	public void setStatisticsdao(StatisticsDao statisticsdao) {
		this.statisticsdao = statisticsdao;
	}
	
	//--------------------- excute core method -----------------------
	public void processOutCallReport(){
		 Connection conn = null; 
	     CallableStatement proc = null;
	     
        try {    
        	conn =  statisticsdao.getHibernateTemplate().
        		getSessionFactory().getCurrentSession().connection();
        	
            proc = conn.prepareCall("{ call outcall_report_pro(?) }");   
            proc.setString(1, getTime("yyyy-MM-dd"));
            proc.execute();  
            
            log.info("....Procedure    !");   
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                    if (null != proc) { 
                        proc.close();
                    }   
                    if (null != conn) { 
                        conn.close(); 
                    }
            } catch (Exception ex) {   
            	
            }   
        }   

	}
}

   

   ここのクラス名は定義されていますか?*ManageImpl接尾辞として定義されているのはなぜですか?
    開発中にspring管理のセッションを直接使用しているので
   普通のPOJOでは事務内でセッションを招かないと報告します
   どうぞご覧ください
   

     //.....
     conn =  statisticsdao.getHibernateTemplate().
        		getSessionFactory().getCurrentSession().connection();
    

    およびspringでaopでトランザクションを構成する方法
    

   <xml?>
   <aop:config proxy-target-class="true">
      <aop:pointcut id="ServiceOperation" 
      expression="execution(* com.chinadim.erp2..*ManageImpl.*(..))"/>
      <aop:advisor advice-ref="txAdvice" 
      pointcut-ref="ServiceOperation"/>
    </aop:config>
    </xml>
    

    ストレージ・プロシージャを実行する方法
     トランザクションの実行方法にも定義されています...
     次はどうやって手を伸ばしても五本の指が見えない夜に触るとすぐに発するのか.
      quartz.xmlを構成するのは明らかです
  

<?xml version="1.0" encoding="UTF-8"?>
<!--   Spring     Schema   -->
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<!-- add by sam 2009-06-25          -->
	<bean id="outCallReport" class="com.chinadim.erp2.datacollection.OutCallReportManageImpl">
		<property name="statisticsdao">
			<ref bean="statisticsdao"/>
		</property>	
	</bean>		
	
<!--                -->
	<!-- add by sam 2009-06-25            -->	
	<bean id="Target_outCallReport" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<!--     -->
	    <property name="targetObject">
		  	<ref bean="outCallReport"/>
		</property>
		
		<!--       -->
		<property name="targetMethod">
			<value>processOutCallReport</value>
		</property>
	</bean>

<!-- add by sam 2009-06-25           JOB -->
	<bean id="Trigger_outCallReport" class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail">
			<ref bean="Target_outCallReport"/>
		</property>
		<property name="cronExpression">
			<value>0 48 15 * * ?</value>
		</property>
	</bean>

	<!-- add by sam 2009-06-25          -->
	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="autoStartup">   
            <value>true</value>   
        </property>   
		<property name="triggers">
			<list>
				<ref local="Trigger_outCallReport"/>
			</list>
		</property>
	</bean>


</beans>

次はレポートを生成するセクションです.
詳細は...
apache POIで実装されたエクスポート・レポート


/**
 * 
 * @version     :2009-5-6    :      POI3.0.2    EXCEL  
 * 
 * @param <T>     ,        javabean    
 */
@SuppressWarnings({"serial","unused","unchecked"})
public abstract class ExportExcel<T> {
	
	public void exportExcel(String title, Collection<T> dataset, OutputStream out) {
		exportExcel(title, null, dataset, out, "yyyy-MM-dd");
	}
	
    public void exportExcel(Collection<T> dataset, OutputStream out) {
        exportExcel("  POI  EXCEL  ", null, dataset, out, "yyyy-MM-dd");
    }

    public void exportExcel(String title, String[] headers, Collection<T> dataset,
		   OutputStream out) {
	     exportExcel(title, headers, dataset, out, "yyyy-MM-dd");
    }

    public void exportExcel(String[] headers, Collection<T> dataset,
         OutputStream out) {
         exportExcel("  POI  EXCEL  ", headers, dataset, out, "yyyy-MM-dd");
    }
    
	public void exportExcel(String[] headers, Collection<T> dataset,
	       OutputStream out, String pattern) {
		exportExcel("  POI  EXCEL  ", headers, dataset, out, pattern);
	}

	   /**
	    *          ,   JAVA     ,
	    *       JAVA               EXCEL         IO   
	    * 
	    * @param title
	    *                 
	    * @param headers
	    *                    
	    * @param dataset
	    *                     ,          javabean       。      
	    *            javabean               String,Date,byte[](    )
	    * @param out
	    *                       ,   EXCEL              
	    * @param pattern
	    *                   ,      。   "yyy-MM-dd"
	    */
	   public void exportExcel(String title, String[] headers,
			   Collection<T> dataset, OutputStream out, String pattern) {

	      //        
	      HSSFWorkbook workbook = new HSSFWorkbook();
	      
	      //       
	      HSSFSheet sheet = workbook.createSheet(title);
	      
	      //           15   
	      sheet.setDefaultColumnWidth((short) 15);
	      
	      //       
	      HSSFCellStyle style = workbook.createCellStyle();
	      
	      //       
	      style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
	      style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
	      style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
	      style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
	      style.setBorderRight(HSSFCellStyle.BORDER_THIN);
	      style.setBorderTop(HSSFCellStyle.BORDER_THIN);
	      style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

	      //       
	      HSSFFont font = workbook.createFont();
	      font.setColor(HSSFColor.VIOLET.index);
	      font.setFontHeightInPoints((short) 12);
	      font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	      
	      //            
	      style.setFont(font);
	      
	      //           
	      HSSFCellStyle style2 = workbook.createCellStyle();
	      style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
	      style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
	      style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
	      style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
	      style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
	      style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
	      style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	      style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

	      //        
	      HSSFFont font2 = workbook.createFont();
	      font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

	      //            
	      style2.setFont(font2);

	      //             
	      HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

	      //           ,    
	      HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));

	      //       
	      comment.setString(new HSSFRichTextString("   POI     !"));

	      //       ,                       .
	      comment.setAuthor("leno");

	      //       
	      HSSFRow row = sheet.createRow(0);

	      for (short i = 0; i < headers.length; i++) {
	         HSSFCell cell = row.createCell(i);
	         cell.setCellStyle(style);
	         HSSFRichTextString text = new HSSFRichTextString(headers[i]);
	         cell.setCellValue(text);
	      }

	      //                   
	      createRowsAndCells(dataset, sheet, 
		row, style2, headers.length, pattern);
	      	      
	      try {
	         workbook.write(out);
	      } catch (IOException e) {
	         e.printStackTrace();
	      }
	   }

	   /**
	    *           
	    */
	   public abstract void createRowsAndCells(Collection<T> dataset, HSSFSheet sheet, 
			   HSSFRow row, HSSFCellStyle style, int columns, String pattern);
	 
	   /**
	    *      
	    * @param args
	    */
	   public static void main(String[] args) {

	   }


}


以上で定義した抽象クラス定義エクスポート・レポートのスタイル・フォーマットの色など
子类が実现するのは継承するだけだ....


/**
 * 
 * @version     :2009-6-25    :
 *
 */
@SuppressWarnings({"serial","unused","unchecked"})
public class ExportExcelOutCallReport extends ExportExcel<OutCallReportWrap>{

	@Override
	public void createRowsAndCells(Collection<OutCallReportWrap> dataset,
			HSSFSheet sheet, HSSFRow row, HSSFCellStyle style, int columns,
			String pattern) {
		
		int index = 0;
		for (OutCallReportWrap oe:dataset){
			index ++;
			//   
			row = sheet.createRow(index);
			for (int i=0; i < columns; i++){
				//         
				HSSFCell cell = row.createCell((short)i);
				cell.setCellStyle(style);
				
				switch (i) {
					case 0: //   :  
						String province = oe.getOutCallReportEntity().getUserObject().getProvince();
						cell.setCellValue(new HSSFRichTextString(province));
						break;
					case 1: //   :  
						String city = oe.getOutCallReportEntity().getUserObject().getCity();
						cell.setCellValue(new HSSFRichTextString(city));
						break;
					case 2: //   :    
						if (null != oe.getOutCallReportEntity().getUserObject().getImporttime()){
							String importTime = getTime(oe.getOutCallReportEntity().
									getUserObject().getImporttime(), "yyyy-MM-dd");
							cell.setCellValue(new HSSFRichTextString(importTime));
						}
						break;
					case 3: //   :    
						String mobile = oe.getOutCallReportEntity().getUserObject().getMobile();
						cell.setCellValue(new HSSFRichTextString(mobile));
						break;
					case 4: //   :      
						if (null != oe.getOutCallReportEntity().getCsAllotAt()){
							String csAllotTime = getTime(oe.getOutCallReportEntity().getCsAllotAt(),"yyyy-MM-dd");
							cell.setCellValue(new HSSFRichTextString(csAllotTime));
						}
						break;
					case 5: //   :      
						if (null != oe.getOutCallReportEntity().getCsCallAt()){
							String csCallTime = getTime(oe.getOutCallReportEntity().getCsCallAt(),"yyyy-MM-dd");
							cell.setCellValue(new HSSFRichTextString(csCallTime));
						}
						break;
					case 6: //   :      
						String csCallResult = UsercommunicateLogEntity.
							getContactResultTreeMapForCallResult(false).get(oe.getOutCallReportEntity().getCsCallResult());
						cell.setCellValue(new HSSFRichTextString(csCallResult));
						break;
					case 7: //   :        
						String csCallResultCause = oe.getOutCallReportEntity().getCsCallResultCause();
						cell.setCellValue(new HSSFRichTextString(csCallResultCause));
						break;
					case 8: //   :      
						String csSeatingNo = oe.getOutCallReportEntity().getCsOperator().getSeatingNo();
						cell.setCellValue(new HSSFRichTextString(csSeatingNo));
						break;
					case 9: //      
						if (null != oe.getOutCallReportEntity().getOrderObject()){
							String asAllotTime = getTime(oe.getOutCallReportEntity().getAsAllotAt(),"yyyy-MM-dd");
							cell.setCellValue(new HSSFRichTextString(asAllotTime));
						}
						break;
					case 10: //      
						if (null != oe.getOutCallReportEntity().getOrderObject()){
							String asCallTime = getTime(oe.getOutCallReportEntity().getAsCallAt(),"yyyy-MM-dd");
							cell.setCellValue(new HSSFRichTextString(asCallTime));
						}
						break;
					case 11: //      
						if (null != oe.getOutCallReportEntity().getOrderObject()){
							String asCallResult = UsercommunicateLogEntity.
							getContactResultTreeMapForCallResult(false).get(oe.getOutCallReportEntity().getAsCallResult());
							cell.setCellValue(new HSSFRichTextString(asCallResult));
						}
						break;
					case 12: //        
						if (null != oe.getOutCallReportEntity().getOrderObject()){
								
							String asCallResultCause = oe.getOutCallReportEntity().getAsCallResultCause();
							cell.setCellValue(new HSSFRichTextString(asCallResultCause));
						}
						break;
					case 13: //      
						if (null != oe.getOutCallReportEntity().getOrderObject()){
							String asSeatingNo = oe.getOutCallReportEntity().getAsOperator().getSeatingNo();
							cell.setCellValue(new HSSFRichTextString(asSeatingNo));
						}
						break;	
					case 14: //    
						if (null != oe.getOutCallReportEntity().getOrderObject()){
							String orderNo = oe.getOutCallReportEntity().getOrderObject().getOrderNo();
							cell.setCellValue(new HSSFRichTextString(orderNo));
						}
						break;	
						
					case 15: //    
						if (null != oe.getOutCallReportEntity().getOrderObject()){
							String orderState = OrdersEntity.getContactResultTreeMapForOrderState(false).
								get(oe.getOutCallReportEntity().getOrderObject().getOrderState());
							cell.setCellValue(new HSSFRichTextString(orderState));
						}
						break;	
						
					case 16: //    
						if (null != oe.getOutCallReportEntity().getOrderObject()){
							String packageNames = oe.getPackageNames();
							cell.setCellValue(new HSSFRichTextString(packageNames));
						}
						break;	
					case 17: //    
						if (null != oe.getOutCallReportEntity().getOrderObject()){
							String orderRemark = oe.getOutCallReportEntity().getOrderObject().getRemark();
							cell.setCellValue(new HSSFRichTextString(orderRemark));
						}
						break;	
				}
			}
		}
	}

}


  多くのコードを貼ってエラーに遭遇し始めました
  少しずつ解決してきた
 
  個人的にはレポートツールの開発に慣れていないときにストレージプロセスを書くのは便利だと思います.
  利益の面でも保障されている
 
 //-----------------------
  次のJ 2 EEレポート開発-->
  友達と一緒に頑張りましょう