Skip to content

Instantly share code, notes, and snippets.

@aarchilla84
Last active April 8, 2020 23:46
Show Gist options
  • Save aarchilla84/5270225 to your computer and use it in GitHub Desktop.
Save aarchilla84/5270225 to your computer and use it in GitHub Desktop.
Acceso al objecto Connection a través de Hibernate 4 para utilizarla como Datasource en Jasperreports
import javax.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.ejb.HibernateEntityManager;
import org.hibernate.jdbc.Work;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
// ...
try{
// Obtenemos el entityManager de JPA. En este caso viene inyectado
HibernateEntityManager em = (HibernateEntityManager)entityManagerProvider.get();
Session session = em.getSession();
session.doWork(new Work()
{
@Override
public void execute(Connection connection) throws SQLException
{
try{
InputStream fileStream = getClass().getResourceAsStream(reportPath);
JasperReport compiledReport = JasperCompileManager.compileReport(fileStream);
JasperPrint jasperPrint = JasperFillManager.fillReport(compiledReport, reportParameters, connection);
// Visualizar o guardar el informe resultante
}
catch(JRException e){
throw new RuntimeException(e);
}
}
});
}
catch(Exception e){
// Tratar el error
}
@dnacher
Copy link

dnacher commented Aug 25, 2016

hola estaba buscando algo como esto, de todas formas veo que pedis el connection por parametro...por lo tanto tendrias que crearlo de todas formas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment