---
title: "实现ireport的JRDataSource接口"
author: "lansky07"
date: "2009-02-09T17:10:01Z"
tags: []
slug: "ireport-jrdatasource"
draft: false
lastmod: "2009-02-09T17:10:01Z"
id: 325796
url: "https://lansky07.iteye.com/blog/325796"
---

在使用Ireport的时候，我从不建议采用这种方式制作报表：

JasperPrint jasperPrint = JasperFillManager.fillReport(String,Map,Connection); 使用hibernate的Session同样不推荐。

原因：

1.性能考虑：

如果你将一个数据库连接交给ireport也就意味着，你必须等待ireport将所有的操作完成才可以回收该链接，如果是在大批量数据显示的情况下（往往如此），将占用很长很长的连接时间，如果实现了JRDataSource接口，先将数据保存到一个list中，那么将花费你极少的时间来处理数据库这部分，之后的数据显示再交给ireport

 

2.数据库部分与ireport耦合太大

尤其是采用hibernate的session 那样带来的耦合度更大，

 

3.不利于代码的重用

如果你是实现了JRDataSource接口，现将数据保存到list中，那么即使你采用ireport来显示数据，在其他的程序中一样的可以随时调用你的getList（）方法

 

4.安全性考虑

越是将数据库暴露到上层，那么应用系统就越危险。

 

其实实现JRDataSource接口非常简单：

只要实现两个方法：

public class LedgerDataSource implements JRDataSource{

private List datas = null ;  
 private int loop = -1 ;   
 private static Logger logger = Logger.getLogger(LedgerDataSource.class.getName());  
 

 

 public Object getFieldValue(JRField field) throws JRException {  
  StatBean temp = (StatBean)this.datas.get(loop);  
  Object rs = "" ;  
  if("month".equals(field.getName())){    
   rs = temp.getMonth();     
  }else if("day".equals(field.getName())){  
   rs = temp.getDay();  
  }else if("voucherNo".equals(field.getName())){  
   rs = temp.getVoucherNo();  
  }else if("debitMoney".equals(field.getName())){  
   rs = temp.getDebitMoney();  
  }else if("creditMoney".equals(field.getName())){  
   rs = temp.getCreditMoney();  
  }else if("DOrc".equals(field.getName())){  
   rs = temp.getDOrc();  
  }else if("summary".equals(field.getName())){  
   rs = temp.getSummary();  
  }else if("balance".equals(field.getName())){  
   rs = temp.getBalance();  
  }  
    
  temp = null ;    
  return rs;  
 }

 public boolean next() throws JRException {  
  loop ++ ;  
  if(loop &gt;= datas.size()){  
   return false;  
  }else{     
   return true ;  
  }    
 }  
   
 public void finalized(){  
  datas = null ;    
 }

}

 

在使用该datasource的时候，只需要JasperPrint jasperPrint = JasperFillManager.fillReport(String,Map,JRDataSource);

\[转载javason的BLOG，感谢！]