博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
BIRT使用ScriptDataSet从POJO中获得数据
阅读量:4054 次
发布时间:2019-05-25

本文共 14884 字,大约阅读时间需要 49 分钟。

 

BIRT使用ScriptDataSet从POJO中获得数据(一)
2011-08-19 09:49

在前面说明过使用Script数据源来获得web service数据源的做法,在实际操作中,发现虽然有BIRT的帮助文件,但同事对BIRTScript数据源的使用还是不太理解,于是写出下文以便帮助使用BIRT的高级特性

 

熟悉了BIRTScript数据源之后,你会感叹BIRT功能之强大,BIRT团队承诺在2.0中加入对数据库连接池的支持,但目前为止,我们还只能通过Script数据源来支持连接池。

 

为了能够自定义数据集合以及支持分页查询、多表查询、数据库连接池或者在DAO中使用Spring+Hibernate或从web Service获取数据等高级特性,我们需要使用BIRTScript数据源来获得数据

下面通过一个示例说明如何使用BIRTScript数据源来通过POJO获取数据:

 

注:

为了使例子不至于因为过于简单而无法说明情况(如同BIRTTutorial那样),在这里我使用了一个简单但完整的DAO层,可直接在项目中使用,同时也为避免过于复杂,本例中没有使用Spring+HibernateWeb Service获得数据源,但从POJO中可很简单的将其改为SH组合或WS

一、一个简单的数据库访问层

 

在开始我们浪费些时间来描述一下DAO层的几个类,以便后面在BIRT中使用它时有所了解。

首先在Eclipse中建立一个Tomcat项目,然后在src中建立一个com.bat.afp.DAOComm包用来封装一个非常简单的DAO类,如下:

o_1.jpg

其中DBUtil为数据库连接类(数据库为Oracle8),使用了DBCP作为数据库连接池,并使用XML文件(dbconfig.xml)来配置数据库连接池的信息

 

DBUtil代码如下:

  
package com.bat.afp.DAOComm;
 
import java.io.File;
 
import java.net.URL;
 
import java.sql.Connection;
 
import java.sql.DriverManager;
 
import java.sql.SQLException;
 
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
 
import org.apache.commons.dbcp.PoolableConnectionFactory;
 
import org.apache.commons.dbcp.PoolingDriver;
 
import org.apache.commons.pool.impl.GenericObjectPool;
 
import org.apache.log4j.BasicConfigurator;
 
import org.apache.log4j.Logger;
 
import org.dom4j.Document;
 
import org.dom4j.DocumentException;
 
import org.dom4j.Element;
 
import org.dom4j.io.SAXReader;
 
 
/*
*
 
 * @author liuyf
 
 
*/
 
public
 
class
 DBUtil 
{
 
 
    
private
 
static
 final Logger    logger        
=
 Logger.getLogger(DBUtil.
class
);
 
 
    
private
 
static
 DBUtil        instance;
 
 
    
private
 GenericObjectPool    connectionPool;
 
 
    
private
 
static
 String        dbUrl;
 
 
    
private
 
static
 String        user;
 
 
    
private
 
static
 String        password;
 
 
    
private
 
static
 
int
            connNumber    
=
 
10
;
 
    
static
 
    
{
 
        BasicConfigurator.configure();
 
       
try
 
       
{
 
            readConfig();
 
        }
 
        
catch
 (DocumentException e)
        
{
 
           e.printStackTrace();
 
       }
    }
 
    
private
 DBUtil()
    
{
        
try
        
{
            initConnectionPool();
        }

        catch (SQLException e)        {

            e.printStackTrace();
        }

        logger.debug(
"
DBUtil init
"
);
  }

   /**     * 读取配置文件

 
     * 
 
     * @throws DocumentException
 
     
*/
 
    
private
 
static
 
void
 readConfig() throws DocumentException
 
    
{
 
        URL url 
=
 DBUtil.
class
.getClassLoader().getResource(
"
dbconfig.xml
"
);
 
        File file 
=
 
new
 File(url.getFile());
 
        
//
 File file = new File("dbconfig.xml");
 
        SAXReader reader 
=
 
new
 SAXReader();
 
        Document document 
=
 reader.read(file);
 
        Element root 
=
 document.getRootElement();
 
        Element dbinfo 
=
 root.element(
"
dbinfo
"
);
 
        dbUrl 
=
 dbinfo.elementText(
"
url
"
);
 
        user 
=
 dbinfo.elementText(
"
user
"
);
 
        password 
=
 dbinfo.elementText(
"
pwd
"
);
 
       String numStr 
=
 dbinfo.elementText(
"
connNumber
"
);
 
        
if
 (numStr 
!=
 
null
)
 
           connNumber 
=
 Integer.parseInt(numStr);
      
   }
 
   
public
 
static
 DBUtil getInstance()
    
{
        
if
 (instance 
==
 
null
)
            
return
 instance 
=
 
new
 DBUtil();
        
else
            
return
 instance;
   
 }
 
 
    
/*
*
 
     * 
     
*/
    
private
 
void
 initConnectionPool() throws SQLException
    
{
 
       DriverManager.registerDriver(
new
 oracle.jdbc.OracleDriver());
 
       connectionPool 
=
 
new
 GenericObjectPool(
null
, connNumber);
        DriverManagerConnectionFactory connectionFactory 
=
 
new
 DriverManagerConnectionFactory(dbUrl, user,
                password);
        PoolableConnectionFactory poolableConnectionFactory 
=
 
new
 PoolableConnectionFactory(
                connectionFactory, connectionPool, 
null
null
false
true
);
        PoolingDriver driver 
=
 
new
 PoolingDriver();
        driver.registerPool(
"
afpdb
"
, connectionPool);
    }
    
public
 Connection getConnection() throws SQLException
    
{
        
return
 DriverManager.getConnection(
"
jdbc:apache:commons:dbcp:afpdb
"
);
    }
}
 
 
 
BIRT使用ScriptDataSet从POJO中获得数据(二)
2011-08-19 10:23

配置文件dbconfig.xml如下:

1<config>

2    <dbinfo>

3        <url>jdbc:oracle:thin:@133.1.72.44:1521:test</url>

4        <user>test</user>

5        <pwd>test</pwd>

6        <connNumber>10</connNumber>

7    </dbinfo>

8</config>

9

这样数据库连接类部分就完成了

下面写一个简单数据访问类,由Table、RowSet和Row三个类组成:

 

Table.java代码如下

 

  1package com.bat.afp.DAOComm;

  2

  3import java.sql.Connection;

  4import java.sql.ResultSet;

  5import java.sql.ResultSetMetaData;

  6import java.sql.SQLException;

  7import java.sql.Statement;

  8import org.apache.log4j.Logger;

  9

 10/**

 11 * @author liuyf

 12 */

 13public class Table {

 14

 15    private static final Logger    logger    = Logger.getLogger(Table.class);

 16

 17    private String                tableName;

 18

 19    public Table(String name) {

 20        this.tableName = name;

 21    }

 22

 23    /**

 24     * 根据条件查出该Table中的某些列

 25     * 

 26     * @param sql

 27     * @param cols

 28     * @return

 29     * @throws SQLException

 30     */

 31    private RowSet executeSQL(String criteria, String[] columns) throws SQLException {

 32        Connection conn = null;

 33        Statement st = null;

 34        ResultSet rs = null;

 35        RowSet rows = new RowSet();

 36        try {

 37            conn = DBUtil.getInstance().getConnection();

 38            st = conn.createStatement();

 39            StringBuffer buffer = new StringBuffer();

 40            for (int i = 0; i < columns.length - 1; ++i) {

 41                buffer.append(columns[i]);

 42                buffer.append(",");

 43            }

 44            buffer.append(columns[columns.length - 1]);

 45            String column = buffer.toString();

 46            rs = st.executeQuery("select " + column + " from " + tableName

 47                    + (criteria == null ? "" : (" where " + criteria)));

 48            int cols = columns.length;

 49            while (rs.next()) {

 50                Row row = new Row();

 51                for (int i = 0; i < cols; ++i) {

 52                    String name = columns[i];

 53                    String value = rs.getString(i + 1);

 54                    row.put(name, value);

 55                }

 56                rows.add(row);

 57            }

 58        }

 59        finally {

 60            try {

 61                if (st != null)

 62                    st.close();

 63            } catch (Exception e) {

 64            }

 65            try {

 66                if (conn != null)

 67                    conn.close();

 68            } catch (Exception e) {

 69            }

 70        }

 71        return rows;

 72    }

 73

 74    private RowSet executeSQL(String sql) throws SQLException {

 75        Connection conn = null;

 76        Statement st = null;

 77        ResultSet rs = null;

 78        RowSet rows = new RowSet();

 79        try {

 80            conn = DBUtil.getInstance().getConnection();

 81            st = conn.createStatement();

 82            rs = st.executeQuery(sql);

 83            ResultSetMetaData rsmd = rs.getMetaData();

 84            int cols = rsmd.getColumnCount();

 85            while (rs.next()) {

 86                Row row = new Row();

 87                for (int i = 0; i < cols; ++i) {

 88                    String name = rsmd.getColumnName(i + 1);

 89                    String value = rs.getString(i + 1);

 90                    row.put(name, value);

 91                }

 92                rows.add(row);

 93            }

 94        }

 95        finally {

 96            try {

 97                if (st != null)

 98                    st.close();

 99            } catch (Exception e) {

100            }

101            try {

102                if (conn != null)

103                    conn.close();

104            } catch (Exception e) {

105            }

106        }

107        return rows;

108    }

109

110    private RowSet execute(String criteria) throws SQLException {

111        Connection conn = null;

112        Statement st = null;

113        ResultSet rs = null;

114        RowSet rows = new RowSet();

115        try {

116            conn = DBUtil.getInstance().getConnection();

117            st = conn.createStatement();

118            rs = st.executeQuery("select * from " + tableName

119                    + (criteria == null ? "" : (" where " + criteria)));

120            ResultSetMetaData rsmd = rs.getMetaData();

121            int cols = rsmd.getColumnCount();

122            while (rs.next()) {

123                Row row = new Row();

124                for (int i = 0; i < cols; ++i) {

125                    String name = rsmd.getColumnName(i + 1);

126                    String value = rs.getString(i + 1);

127                    row.put(name, value);

128                }

129                rows.add(row);

130            }

131        }

132        finally {

133            try {

134                if (st != null)

135                    st.close();

136            } catch (Exception e) {

137            }

138            try {

139                if (conn != null)

140                    conn.close();

141            } catch (Exception e) {

142            }

143        }

144        return rows;

145    }

146

147    /**

148     * 根据条件和给出的列名查询某些列的值

149     * 

150     * @param criteria

151     * @param columns

152     * @return

153     * @throws SQLException

154     */

155    public RowSet getRowsOfSomeColumn(String criteria, String[] columns) throws SQLException {

156        RowSet rs = executeSQL(criteria, columns);

157        return rs;

158    }

159

160    /**

161     * 根据SQL语句查询并返回行集

162     * 

163     * @param sql

164     * @return

165     * @throws SQLException

166     */

167    public RowSet getRowsBySql(String sql) throws SQLException {

168        RowSet rs = executeSQL(sql);

169        return rs;

170    }

171

172    /**

173     * 根据查询条件返回查到的第一行数据

174     * 

175     * @param criteria

176     * @return

177     * @throws SQLException

178     */

179    public Row getRow(String criteria) throws SQLException {

180        RowSet rs = execute(criteria);

181        return rs.get(0);

182    }

183

184    /**

185     * 根据查询条件返回行集 查询条件为sql语句中where后的条件 为null则无条件

186     * 

187     * @param criteria

188     * @return

189     * @throws SQLException

190     */

191    public RowSet getRows(String criteria) throws SQLException {

192        RowSet rs = execute(criteria);

193        return rs;

194    }

195

196    public RowSet getRows(String columnName, String columnvalue) throws SQLException {

197        if(columnName == null || columnName.equals("")){

198            return null;

199        }

200        String SQL = "select * from " + tableName + " where " + columnName + " = " + columnvalue;

201        RowSet rs = executeSQL(SQL);

202        return rs;

203        

204    }

205

206    /**

207     * 查询该Table的所有数据

208     * 

209     * @return

210     * @throws SQLException

211     */

212    public RowSet getRows() throws SQLException {

213        return getRows(null);

214    }

215

216    /**

217     * 插入行

218     * 

219     * @param row

220     * @throws SQLException

221     */

222    public void putRow(Row row) throws SQLException {

223        putRow(row, null);

224    }

225

226    /**

227     * 插入行或更新行 如conditions为null,则为插入 如conditions不为null,则为更新

228     * 

229     * @param row

230     * @param conditions

231     * @throws SQLException

232     */

233    public void putRow(Row row, String conditions) throws SQLException {

234        Connection conn = null;

235        Statement st = null;

236        try {

237            String ss = "";

238            if (conditions == null) {

239                ss = "INSERT INTO " + tableName + " VALUES (";

240                for (int i = 0; i < row.length(); ++i) {

241                    String v = row.get(i);

242                    ss += "'" + v + "'";

243                    if (i != row.length() - 1)

244                        ss += ", ";

245                }

246                ss += ")";

247            } else {

248                ss = "UPDATE " + tableName + " SET ";

249                for (int i = 0; i < row.length(); ++i) {

250                    String k = row.getKey(i);

251                    String v = row.get(i);

252                    ss += k + "='" + v + "'";

253                    if (i != row.length() - 1)

254                        ss += ", ";

255                }

256                ss += " WHERE ";

257                ss += conditions;

258            }

259            logger.debug("Sql: " + ss);

260            conn = DBUtil.getInstance().getConnection();

261            st = conn.createStatement();

262            st.executeUpdate(ss);

263        }

264        finally {

265            try {

266                if (st != null)

267                    st.close();

268            } catch (Exception e) {

269            }

270            try {

271                if (conn != null)

272                    conn.close();

273            } catch (Exception e) {

274            }

275        }

276    }

277

278    public void delRow(Row row) throws SQLException {

279        Connection conn = null;

280        Statement st = null;

281        try {

282            String ss = "";

283            ss = "delete from " + tableName + " where ";

284            for (int i = 0; i < row.length(); ++i) {

285                String k = row.getKey(i);

286                String v = row.get(i);

287                ss += k + "='" + v + "'";

288                if (i != row.length() - 1)

289                    ss += " and ";

290            }

291            conn = DBUtil.getInstance().getConnection();

292            st = conn.createStatement();

293            st.executeUpdate(ss);

294        }

295        finally {

296            try {

297                if (st != null)

298                    st.close();

299            } catch (Exception e) {

300            }

301            try {

302                if (conn != null)

303                    conn.close();

304            } catch (Exception e) {

305            }

306        }

307    }

308

309    public void delRow(String conditions) throws SQLException {

310        Connection conn = null;

311        Statement st = null;

312        try {

313            String ss = "";

314            ss = "delete from " + tableName + " where ";

315            ss += conditions;

316            conn = DBUtil.getInstance().getConnection();

317            st = conn.createStatement();

318            st.executeUpdate(ss);

319        } catch (SQLException se) {

320            se.printStackTrace();

321        }

322        finally {

323            try {

324                if (st != null)

325                    st.close();

326            } catch (Exception e) {

327            }

328            try {

329                if (conn != null)

330                    conn.close();

331            } catch (Exception e) {

332            }

333        }

334    }

 
 
 
BIRT使用ScriptDataSet从POJO中获得数据(三)
2011-08-19 10:25

RowSet.java代表行的集合,代码如下:

 1
package com.bat.afp.DAOComm;
 2
 3
import java.util.Iterator;
 4
import java.util.Vector;
 5
 6
/*
*
 7
 * @author liuyf
 8
 
*/
 9
public
 
class
 RowSet 
{
10
11
    
private
 Vector
<
Row
>
    vector    
=
 
new
 Vector
<
Row
>
();
12
13
    
public
 RowSet() 
{
14
    }
15
16
    
public
 
void
 add(Row row) 
{
17
        vector.addElement(row);
18
    }
19
20
    
public
 
int
 length() 
{
21
        
return
 vector.size();
22
    }
23
24
    
public
 Row 
get
(
int
 which) 
{
25
        
return
 (Row) vector.elementAt(which);
26
    }
27
    
28
    
public
 Iterator getIterator()
{
29
        
return
 vector.iterator();
30
    }
31
32
    
public
 
void
 dump() 
{
33
        Iterator
<
Row
>
 itr 
=
 vector.iterator();
34
        
for
 (;itr.hasNext();) 
{
35
            itr.next().dump();
36
        }
37
    }
38
}
39

Row.java代表数据库中的一行数据,代码如下:

 1
package com.bat.afp.DAOComm;
 2
 3
import java.util.Hashtable;
 4
import java.util.Iterator;
 5
import java.util.Vector;
 6
 7
/*
*
 8
 * @author liuyf
 9
 
*/
10
public
 
class
 Row 
{
11
12
    
private
 Vector
<
String
>
                ordering    
=
 
new
 Vector
<
String
>
();
13
14
    
private
 Hashtable
<
String, String
>
    hashtable    
=
 
new
 Hashtable
<
String, String
>
();
15
16
    
public
 Row() 
{
17
    }
18
19
    
public
 
void
 put(String name, String value) 
{
20
        
if
 (
!
hashtable.containsKey(name))
21
            ordering.addElement(name);
22
        hashtable.put(name, value);
23
    }
24
25
    
public
 
int
 length() 
{
26
        
return
 hashtable.size();
27
    }
28
29
    
public
 String 
get
(String name) 
{
30
        
if
(hashtable.
get
(name)
!=
null
)
{
31
            
return
 hashtable.
get
(name);
32
        }
else
 
if
(hashtable.
get
(name.toLowerCase())
!=
null
)
{
33
            
return
 hashtable.
get
(name.toLowerCase());
34
        }
else
 
if
(hashtable.
get
(name.toUpperCase())
!=
null
)
{
35
            
return
 hashtable.
get
(name.toUpperCase());
36
        }
37
        
38
        
return
 
null
;
39
    }
40
41
    
public
 String 
get
(
int
 which) 
{
42
        String key 
=
 ordering.elementAt(which
-
1
);
43
        
return
 hashtable.
get
(key);
44
    }
45
46
    
public
 String getKey(
int
 which) 
{
47
        String key 
=
 ordering.elementAt(which
-
1
);
48
        
return
 key;
49
    }
50
51
    
public
 
void
 dump() 
{
52
        Iterator
<
String
>
 itr 
=
 hashtable.keySet().iterator();
53
        
for
 (; itr.hasNext();) 
{
54
            String name 
=
 itr.next();
55
            String value 
=
 hashtable.
get
(name);
56
            System.
out
.print(name 
+
 
"
=
"
 
+
 value 
+
 
"
"
);
57
        }
58
    }
59
}
60
 
 
 
 
 
BIRT使用ScriptDataSet从POJO中获得数据(四)
2011-08-19 10:26

开始说正题

二、建立使用ScriptDataSourceScripteDataSetBIRT报表

在你的Web项目中建立一个report目录,并在其中建立一个报表文件,如下:

 

首先,根据BIRTHelp文档中的教程,建立一个ScriptDataSource

然后建立ScriptDataSet

o_Snap3.jpg

然后鼠标右击建立的DataSet,选择编辑,在左边选择‘输出列’,为其添加三个输出列,类型为‘任何’,建立后DataSet如下:
o_Snap4.jpg

三、编写ScriptDataSet方法

ScriptDataSet的主要方法有三个:openfetchclose

打开rptdesign文件,用鼠标点击srcDataSet,并在报表文件窗口下方选择‘代码’,就可以看到这些方法,这些是一些类javaScript的代码,并提供了一些BIRT自己的函数,下面说明这三个方法:

l         Open方法:

Open方法用于引入java包,并创建数据库访问资源

写入如下代码:

(其中in_sys_user是数据库中的表)

o_Snap5.jpg
l         fetch方法:

fetch方法用于取得数据并为报表复制

代码如下:

o_Snap6.jpg

l         close方法:

close方法用于关闭资源

代码如下:

o_Snap7.jpg

 

 

BIRT使用ScriptDataSet从POJO中获得数据(五)
2011-08-19 10:29

四、预览结果

使用BIRT提供的预览窗口来预览所制作的报表,这是BIRT必须知道该如何找到在Script中引用的类,而BIRT的预览窗口是使用一个内嵌的web服务器来预览的,所以,我们需要将用于数据库资源访问的类和在script中使用的类打包成jar放入到这个web-appclasspath下。

这个web-app是作为一个Eclipseplugin存在的,它位置在:

<ECLIPSE_HOME>\plugins\org.eclipse.birt.report.viewer_1.0.0

将打包好的jar文件放入到该plugin下的如下目录:

<ECLIPSE_HOME>\plugins\org.eclipse.birt.report.viewer_1.0.0\birt\WEB-INFO\lib

然后将你的数据库访问组件所依赖的jar文件都一并拷贝到这个lib目录下,并将数据库访问组件需要的配置文件放入到WEB-INFO下,以便其可以在这个web应用的classpath中找到自己的配置文件

 

另外,如果使用配置文件的话,需要象在Tomcat中使用配置文件一样,将配置文件拷贝到以下目录,以便dom4j能够找到

<ECLIPSE_HOME>\plugins\org.eclipse.birt.report.viewer_1.0.0\birt\WEB-INFO\classes

 

最后,也是最重要的一点!也是困扰了我几个小时的问题

教程中没有提到,拷贝完自己的这些数据库访问组件后,需要重启Eclipse才能使用!!?

这个viewerweb程序会在每次Eclipse启动时启动,并读入这些配置信息,运行期则不会在重新装载配置信息

 

―――――――――――

另外,还有另一种方法来发布数据库访问组件,就是将编译好的class文件放入到这个WEB-INFO目录的classes目录下,但要注意要建立目录以匹配自己的包结构,就如同普通的Tomcat程序那样

―――――――――――

预览结果:(图)

o_Snap8.jpg

五、发布环境中运行

发布时的操作要比预览时简单的多,你可以将这个报表文件当作你的web程序中的一个JSP文件来通过URL来访问,并可以在URL中传递参数给报表文件,以便指定查询条件,这些问题在BIRT的教程中讲的很清楚了,这里就不再说明

转载地址:http://potci.baihongyu.com/

你可能感兴趣的文章
scala中的函数组合器map,foreach,flatmap,flatten,filter,zip等用法
查看>>
Spark RDD API
查看>>
spark中算子详解:aggregateByKey
查看>>
Spark自定义排序
查看>>
Spark2.x 如何实现自定义排序(利用元组,类--隐式转换Ordering,Ordered等实现)
查看>>
Spark配置参数
查看>>
使用kafkachannel 启动flume报错
查看>>
Git常用命令
查看>>
ssh 如何方便的切换到其他节点??
查看>>
rank() over,dense_rank() over,row_number() over的区别
查看>>
只要你要,只要我有
查看>>
常用数据库的JDBC驱动程序写法
查看>>
回溯法迷宫求解
查看>>
JSP中文乱码总结
查看>>
AspectJ下载和安装
查看>>
Java-IO-File类
查看>>
Java-IO-java的IO流
查看>>
Java-IO-字节流和字符流
查看>>
Java-IO-输入/输出流体系
查看>>
Java实现DES加密解密
查看>>