2

I want to get the current connection from Spring context and then pass to my JasperPrint object.

Something like this:

 //java.sql.Connection con = StringContext.getConnection();
 JasperPrint jp = JasperFillManager.fillReport("reports/my_report.jasper", parameters, con);

How can I make this works?

ps: I've tried using DataSourceUtils, but the getConnection() method needs a DataSource object as parameter, where do I get this object?

Alex K
  • 22,315
  • 19
  • 108
  • 236
Georgy Passos
  • 139
  • 1
  • 2
  • 9
  • Use the `DataSourceUtils`, but I would suggest taking a look at the Jasper support in Spring which might give you some other insights. – M. Deinum Dec 22 '14 at 14:33
  • @M.Deinum , but how to do that? The DataSourceUtils.getConnection() method needs a DataSource parameter, where do I get this parameter? – Georgy Passos Dec 22 '14 at 14:49
  • 1
    You can just inject the `DataSource` in the class you are creating the `JasperPrint` from (I'm assuming that that is a spring managed class). – M. Deinum Dec 22 '14 at 14:50

2 Answers2

1

You may need something like this:

@Component
class JRExporter{
    @Autowired
    protected DataSource localDataSource;

    public void export(){
      java.sql.Connection con = localDataSource.getConnection()
      JasperPrint jp = JasperFillManager.fillReport("reports/my_report.jasper", parameters, con);
    }
Lyudvig
  • 87
  • 1
  • 2
  • 9
  • but the JRExporter must be Spring component – Lyudvig Feb 06 '15 at 08:29
  • I'm using Hikari Datasource and when I autowire the datasource as shown then getConnection() it gives me a connection leak error every time I tun the report – S.Serem Apr 06 '20 at 06:27
0

The best way is to use the connection of the current transaction (as shown here https://stackoverflow.com/a/8428795/6230007), using DataSourceUtils.getConnection()

@Autowired
private ApplicationContext applicationContext; 
...

JasperPrint jp = JasperFillManager.fillReport("my_report.jasper", params,
DataSourceUtils.getConnection((DataSource)applicationContext.getBean("dataSource")));
Panos K.
  • 61
  • 4