Reputation: 2293
I am using Grails 2.2.1, and I have a custom dataSource injected into the service so that I can execute some SQL queries.
Upon first execution, there is a dataSource, but on each subsequent call, the reference to the dataSource has become null.
class ReportService {
def dataSource_myds
Object[] reportRecords(int a) {
String query = "SELECT ..."
Object[] resultSet;
Sql sql = new Sql(dataSource_myds)
// ^ Here the NullPointerException is thrown
// But it always works at the first execution
sql.eachRow(query, [a]) {
...
resultSet += result
}
return resultSet
}
}
class ReportController {
ReportService reportService
def report = {
...
Object[] resultSet1 = reportService.reportRecords(1)
...
Object[] resultSet2 = reportService.reportRecords(2)
// ^ java.lang.NullPointerException : Must specify a non-null Connection
...
}
}
Has anyone ever seen this before, and if so, how can I avoid this?
Here is my DataSource.groovy
environments {
development {
dataSource_myds {
url = "jdbc:oracle:thin:@..."
driverClassName = "oracle.jdbc.driver.OracleDriver"
username = "..."
password = "..."
}
}
}
Upvotes: 3
Views: 3490
Reputation: 91
I had a similar issue and I got it fixed. Firstly, make sure your Service class is in the grails-app/services
folder. Secondly, you need to make sure you get the object of the service class using the injection mechanism and not by using the constructor. I had my service class in the right folder but I was trying to create the instance of the service class as MyService.instance
in my controller and having the issue of null dataSource/connection. Then I tried def myService
in my controller instead of MyService.instance
and it worked. Hope this helps. Thanks
Upvotes: 1
Reputation: 10001
James Kleeh's comment solved it for me - grails clean
and then restart the app.
Upvotes: 1
Reputation: 2293
Solved avoiding 2 subsequent calls to the service. It seems the framework nulls the service connection after the first call from the controller.
Upvotes: 1
Reputation: 1344
Try, to use resources.groovy way as well. This will also give you option for environment basis datasource.
Explained well on the link given below:
Grails 2 multiple dynamic datasources in services
Thanks
Upvotes: 1