micronautmicronaut-data

Get Connection from injected DataSource throws exception with multiple datasources in Micronaut Data JDBC


Couldn't get connection from injected DataSource like spring and as written in documentation(Configuring Multiple Data Sources) https://micronaut-projects.github.io/micronaut-sql/latest/guide/#:~:text=Configuring%20Multiple%20Data%20Sources throws

Suppressed: io.micronaut.transaction.exceptions.NoTransactionException: No current transaction present. Consider declaring @Transactional on the surrounding method
        at io.micronaut.transaction.jdbc.TransactionalConnectionInterceptor.intercept(TransactionalConnectionInterceptor.java:65)
        at io.micronaut.aop.chain.MethodInterceptorChain.proceed(MethodInterceptorChain.java:137)
        at io.micronaut.transaction.jdbc.TransactionalConnection$Intercepted.close(Unknown Source)
        at com.demo.service.DemoService.processRecords(DemoService.java:116)
        ... 11 common frames omitted
    Caused by: io.micronaut.transaction.jdbc.exceptions.CannotGetJdbcConnectionException: No current JDBC Connection found. Consider wrapping this call in transactional boundaries.
        at io.micronaut.transaction.jdbc.DataSourceUtils.doGetConnection(DataSourceUtils.java:135)
        at io.micronaut.transaction.jdbc.DataSourceUtils.getConnection(DataSourceUtils.java:93)
        at io.micronaut.transaction.jdbc.TransactionalConnectionInterceptor.intercept(TransactionalConnectionInterceptor.java:63)
        ... 14 common frames omitted

Solution

  • I solved my problem by unwrapping injected DataSource (more):

    DataSource db1Ds = ((DelegatingDataSource) db1DataSource).getTargetDataSource();
    Connection db1Conn = db1Ds.getConnection();
    /* or
    Connection db1Conn = ((DelegatingDataSource) db1DataSource).getConnection();
    */
    

    I don't know that there is short solution or not.