Hibernate get Connection object for JasperRunManag

2019-08-06 05:30发布

问题:

I'm using Hibernate 3.2.5 in a project and Jasper 3.7.2 to generate Some Reports for the application.

Is there any way to get a Connection Object from a HibernateSessionFactory Object? I wanna handle only one connection, because at this time I have to have a properties file for the ODBC connection that is gonna handle the Jasper through the JasperRunManager statics methods, and also Hibernate for other side.

This is the method I need to pass the connection:

byte[] net.sf.jasperreports.engine.JasperRunManager.runReportToPdf(InputStream inputStream, Map parameters, Connection conn) throws JRException

Thanks in advance. :)

回答1:

I had the same problem with hibernate 4 and here is solution

Session ses = ...
final InputStream finalCompiledReportStream = compiledReportStream;
final OutputStream finalByteArrayOutputStream = byteArrayOutputStream;
ses.doWork(new Work() {
    public void execute(Connection connection) throws SQLException {
       try {
           JasperFillManager.fillReportToStream(finalCompiledReportStream, finalByteArrayOutputStream, parameters, connection);
       } catch (JRException e) {
           ReportAction.this.logger.error(e);
       }
    }
});


回答2:

This works awesomely and you can use the connection object elsewhere where you may need it in the code. doWork may need you to keep doing that many times but creating a connection object nice is a cleaner solution.

SessionImpl sessionImpl = (SessionImpl) session;
Connection conn = sessionImpl.connection();

Where session is the name of the Hibernate Session object