I have a JSON object returned from Groovy's HTTPBuilder. THE JSON contains some null values represented as JSONNull objects. The problem is that when I try to render the JSON back in a response, I get an error when it tries to render the JSONNull. I get a response that is only partially rendered. I want it to render as "null". How do I do this?
Code:
render(contentType: "text/json") {
listOfJSONObjectsThatIncludeJSONNulls
}
Error:
| Error 2013-09-17 11:33:56,965 [http-bio-8080-exec-4] ERROR errors.GrailsExceptionResolver - JSONException occurred when processing request: [GET] /my/action
Object is null. Stacktrace follows:
Message: Object is null
Line | Method
->> 69 | isEmpty in net.sf.json.JSONNull
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 199 | value in grails.converters.JSON
| 162 | convertAnother in ''
| 199 | value in ''
| 162 | convertAnother in ''
| 199 | value in ''
| 162 | convertAnother in ''
| 199 | value in ''
| 162 | convertAnother in ''
| 199 | value in ''
| 162 | convertAnother in ''
| 199 | value in ''
| 162 | convertAnother in ''
| 199 | value in ''
| 134 | render . . . . in ''
| 150 | render in ''
| 63 | doCall . . . . in myproject.MyController$_index_closure1_closure2_closure4$$EOHirVeS
| 477 | doRequest in groovyx.net.http.HTTPBuilder
| 417 | doRequest . . in ''
| 349 | request in ''
| 43 | doCall . . . . in myproject.MyController$_index_closure1$$EOHirVeS
| 477 | doRequest in groovyx.net.http.HTTPBuilder
| 268 | get . . . . . in ''
| 31 | index in myproject.MyController$$EOHirVeS
| 895 | runTask . . . in java.util.concurrent.ThreadPoolExecutor$Worker
| 918 | run in ''
^ 680 | run . . . . . in java.lang.Thread
Partially Rendered Output:
[{"keyWithNullValue":{"array":false,"class":"net.sf.json.JSONNull"
I used the following code to render JSONNull as an empty string.
grails.converters.JSON.registerObjectMarshaller(JSONNull, { return "" })
I think you can fix it by specifying the below one in BootStrap
JSONObject.NULL.metaClass.asBoolean = {-> false}
Have a look at: how to get a real null value instead of a JSONObject.NULL value when parsing JSON in grails
Related
I'm trying to get the JSR-311 plugin working with Grails 2.3.7. I'm using version 0.10, because I think 0.11 requires Grails 2.4.
I've used the generate-resource command to create an end point for my domain class Product. Two resource classes are created, ProductCollectionResource and ProductResource. I've tweaked them a bit, but essentially they look like this:
ProductCollectionResource
#Path('/api/products')
#Consumes(['application/json'])
#Produces(['application/json'])
class ProductCollectionResource {
def productResourceService
#Path('{id}')
#GET
ProductResource getResource(#PathParam('id') Long id) {
new ProductResource(productResourceService: productResourceService, id:id)
}
#GET
Response readAll(#QueryParam("max") Integer max, #QueryParam("offset") Integer offset) {
ok productResourceService.readAll(max, offset)
}
}
ProductResource
#Consumes(['application/json'])
#Produces(['application/json'])
class ProductResource {
def productResourceService
def id
#GET
Response read() {
ok productResourceService.read(id)
}
}
The readAll method in ProductCollectionResource works fine - when I hit it, I get back a list of products, however when I try to access a specific product by id (on /api/products/123), I get the following error:
Caused by MessageException: A message body writer for Java class com.myapp.ProductResource, and Java type class com.myapp.ProductResource, and MIME media type application/json was not found
->> 285 | write in com.sun.jersey.spi.container.ContainerResponse
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1479 | _handleRequest in com.sun.jersey.server.impl.application.WebApplicationImpl
| 1391 | handleRequest . . in ''
| 1381 | handleRequest in ''
| 416 | service . . . . . in com.sun.jersey.spi.container.servlet.WebComponent
| 538 | service in com.sun.jersey.spi.container.servlet.ServletContainer
| 716 | service . . . . . in ''
| 193 | process in org.grails.jaxrs.web.JaxrsContext$JaxrsServiceImpl
| 45 | handle . . . . . . in org.grails.jaxrs.JaxrsController
| 195 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter . . . . . in grails.plugin.cache.web.filter.AbstractFilter
| 150 | invoke in net.bull.javamelody.JspWrapper
| 285 | invoke . . . . . . in net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler
| 198 | doFilter in net.bull.javamelody.MonitoringFilter
| 176 | doFilter . . . . . in ''
| 67 | doFilter . . . . . in ''
| 53 | doFilter in grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter
| 82 | doFilter in grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter
| 63 | doFilter . . . . . in com.odobo.grails.plugin.springsecurity.rest.RestLogoutFilter
| 46 | doFilterInternal in org.grails.jaxrs.web.JaxrsFilter
| 82 | doFilter . . . . . in com.brandseye.cors.CorsFilter
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run in java.lang.Thread
So it looks like it's trying to marshall my ProductResource class to JSON, which I think isn't really what I want. I think it should be invoking the ProductResource.read() method, and marshalling the returned value from that method to JSON.
I have no experience in Grails whatsoever, but from a pure Jersey standpoint, look at what you got here
#Path('{id}')
#GET
ProductResource getResource(#PathParam('id') Long id) {
This is resource method (endpoint). So the ProductsResource will be treated as the response body, just like any other resource method.
You seem to be trying to use the sub-resource locator functionality, forwarding to the ProductsResource class. For that to work, the sub-resource locator (getResource) should not have an #HttpMethod annotation. That's one of the factors that differentiates a resource method from a sub-resource locator.
So just remove the #GET from the getResource method. The #GET is already established by the read() method in the ProductsResource, which is what will be called.
For more information, see the documentation for Sub-Resource Locators
Using Grails Database Migration Plugin 1.4 I want have the following structure of my existing database:
class StickerGroup {
}
Now I added the class Company and updated the class StickerGroup:
class StickerGroup {
static constraints = { company nullable: true, unique: true }
static belongsTo = [company: Company]
}
class Company {
static hasOne = [stickerGroup: StickerGroup]
}
I created the migration file and then I perform grails dbm-update. After that I get the following error log:
2015-01-20 15:03:49,549 [main] ERROR liquibase - Change Set 2015-01-20-update-Company.groovy::1421762562430-2::mg (generated) failed. Error: Error executing SQL ALTER TABLE `sticker_group` ADD `company_id` VARCHAR(10) NOT NULL UNIQUE: Duplicate entry '' for key 'company_id'
Message: Error executing SQL ALTER TABLE `sticker_group` ADD `company_id` VARCHAR(10) NOT NULL UNIQUE: Duplicate entry '' for key 'company_id'
Line | Method
->> 62 | execute in liquibase.executor.jvm.JdbcExecutor
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 104 | execute in ''
| 1091 | execute . . . . . in liquibase.database.AbstractDatabase
| 1075 | executeStatements in ''
| 317 | execute . . . . . in liquibase.changelog.ChangeSet
| 27 | visit in liquibase.changelog.visitor.UpdateVisitor
| 58 | run . . . . . . . in liquibase.changelog.ChangeLogIterator
| 114 | update in liquibase.Liquibase
| 26 | doCall . . . . . in DbmUpdate$_run_closure1_closure2
| 59 | doCall in _DatabaseMigrationCommon_groovy$_run_closure2_closure11
| 133 | executeInSession in grails.plugin.databasemigration.MigrationUtils
| 51 | doCall in _DatabaseMigrationCommon_groovy$_run_closure2
^ 25 | doCall . . . . . in DbmUpdate$_run_closure1
Caused by MySQLIntegrityConstraintViolationException: Duplicate entry '' for key 'company_id'
->> 377 | handleNewInstance in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 360 | getInstance in ''
| 971 | createSQLException in com.mysql.jdbc.SQLError
| 3887 | checkErrorPacket in com.mysql.jdbc.MysqlIO
| 3823 | checkErrorPacket in ''
| 2435 | sendCommand in ''
| 2582 | sqlQueryDirect . in ''
| 2526 | execSQL in com.mysql.jdbc.ConnectionImpl
| 2484 | execSQL . . . . . in ''
| 848 | execute in com.mysql.jdbc.StatementImpl
| 742 | execute . . . . . in ''
| 92 | doInStatement in liquibase.executor.jvm.JdbcExecutor$1ExecuteStatementCallback
| 55 | execute . . . . . in liquibase.executor.jvm.JdbcExecutor
| 104 | execute in ''
| 1091 | execute . . . . . in liquibase.database.AbstractDatabase
| 1075 | executeStatements in ''
| 317 | execute . . . . . in liquibase.changelog.ChangeSet
| 27 | visit in liquibase.changelog.visitor.UpdateVisitor
| 58 | run . . . . . . . in liquibase.changelog.ChangeLogIterator
| 114 | update in liquibase.Liquibase
| 26 | doCall . . . . . in DbmUpdate$_run_closure1_closure2
| 59 | doCall in _DatabaseMigrationCommon_groovy$_run_closure2_closure11
| 133 | executeInSession in grails.plugin.databasemigration.MigrationUtils
| 51 | doCall in _DatabaseMigrationCommon_groovy$_run_closure2
^ 25 | doCall . . . . . in DbmUpdate$_run_closure1
liquibase.exception.MigrationFailedException: Migration failed for change set 2015-01-20-update-Company.groovy::1421762562430-2::mg (generated):
Reason: liquibase.exception.DatabaseException: Error executing SQL ALTER TABLE `sticker_group` ADD `company_id` VARCHAR(10) NOT NULL UNIQUE: Duplicate entry '' for key 'company_id':
Caused By: Error executing SQL ALTER TABLE `sticker_group` ADD `company_id` VARCHAR(10) NOT NULL UNIQUE: Duplicate entry '' for key 'company_id':
Caused By: Duplicate entry '' for key 'company_id'
at liquibase.changelog.ChangeSet.execute(ChangeSet.java:347)
at liquibase.changelog.visitor.UpdateVisitor.visit(UpdateVisitor.java:27)
at liquibase.changelog.ChangeLogIterator.run(ChangeLogIterator.java:58)
at liquibase.Liquibase.update(Liquibase.java:114)
at DbmUpdate$_run_closure1_closure2.doCall(DbmUpdate:26)
at _DatabaseMigrationCommon_groovy$_run_closure2_closure11.doCall(_DatabaseMigrationCommon_groovy:59)
at grails.plugin.databasemigration.MigrationUtils.executeInSession(MigrationUtils.groovy:133)
at _DatabaseMigrationCommon_groovy$_run_closure2.doCall(_DatabaseMigrationCommon_groovy:51)
at DbmUpdate$_run_closure1.doCall(DbmUpdate:25)
Caused by: liquibase.exception.DatabaseException: Error executing SQL ALTER TABLE `sticker_group` ADD `company_id` VARCHAR(10) NOT NULL UNIQUE: Duplicate entry '' for key 'company_id'
at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:62)
at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:104)
at liquibase.database.AbstractDatabase.execute(AbstractDatabase.java:1091)
at liquibase.database.AbstractDatabase.executeStatements(AbstractDatabase.java:1075)
at liquibase.changelog.ChangeSet.execute(ChangeSet.java:317)
... 8 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '' for key 'company_id'
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.Util.getInstance(Util.java:360)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:971)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:848)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:742)
at liquibase.executor.jvm.JdbcExecutor$1ExecuteStatementCallback.doInStatement(JdbcExecutor.java:92)
at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:55)
... 12 more
How can I fix this error?
I have switched from Grails 2.2.4 to Grails 2.4.3 and experienced bad problems with my IntelliJ IDEA 13.1.4 IDE.
After creating a clean Grails 2.4.3 project and adding a clean controller class I start the project via "run-app" in IntelliJ IDEA. Afterwards I change something in the controller and I get the following exceptions:
2014-09-29 18:45:41,801 [Thread-11] ERROR plugins.AbstractGrailsPluginManager - Plugin
[controllers:2.4.3] could not reload changes to file [D:\VS\Eclipse Workspace\xx\grails-app\controllers\com\xx\backoffice\MaintenanceController.groovy]: Cannot get property 'cacheOperationSource' on null object
Message: Cannot get property 'cacheOperationSource' on null object
Line | Method
->> 184 | doCall in CacheGrailsPlugin$_closure4
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
.....................Error
|
2014-09-29 18:45:43,276 [FileSystemWatcher: files=#175 cl=groovy.lang.GroovyClassLoader#177f04d9] ERROR agent.Watcher - FileWatcher caught serious error, see cause
Message: loader (instance of org/springsource/loaded/ChildClassLoader): attempted duplicate class definition for name: "com/xx/MaintenanceController$$DOrGoSVQ"
Line | Method
->> 791 | defineClass in java.lang.ClassLoader
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 634 | defineClass in ''
^ 722 | run . . . . in java.lang.Thread
My BuildConfig.groovy:
grails.servlet.version = "3.0" // Change depending on target container compliance (2.5 or 3.0)
grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
grails.project.work.dir = "target/work"
grails.project.target.level = 1.6
grails.project.source.level = 1.6
//grails.project.war.file = "target/${appName}-${appVersion}.war"
grails.reload.enabled = true
forkConfig = [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false]
grails.project.fork = [
// configure settings for compilation JVM, note that if you alter the Groovy version forked compilation is required
// compile: [maxMemory: 256, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
// configure settings for the test-app JVM, uses the daemon by default
test: forkConfig,
// configure settings for the run-app JVM
run: forkConfig,
// configure settings for the run-war JVM
war: forkConfig,
// configure settings for the Console UI JVM
console: forkConfig
]
grails.project.dependency.resolver = "maven" // or ivy
grails.dependency.cache.dir = "${userHome}/.m2/repository"
grails.project.dependency.resolution = {
// inherit Grails' default dependencies
inherits("global") {
// specify dependency exclusions here; for example, uncomment this to disable ehcache:
// excludes 'ehcache'
}
log "info" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
checksums true // Whether to verify checksums on resolve
legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility
repositories {
inherits true // Whether to inherit repository definitions from plugins
grailsPlugins()
grailsHome()
mavenLocal()
grailsCentral()
mavenCentral()
// uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
mavenRepo "http://repository.codehaus.org"
//mavenRepo "http://download.java.net/maven/2/"
//mavenRepo "http://repository.jboss.com/maven2/"
}
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
// runtime 'mysql:mysql-connector-java:5.1.29'
// runtime 'org.postgresql:postgresql:9.3-1101-jdbc41'
test "org.grails:grails-datastore-test-support:1.0-grails-2.4"
runtime 'mysql:mysql-connector-java:5.1.32'
}
plugins {
// plugins for the build system only
build ":tomcat:7.0.55"
// plugins for the compile step
compile ":scaffolding:2.1.2"
compile ':cache:1.1.8'
compile ":asset-pipeline:1.9.6"
compile ":shiro:1.2.1"
compile ":less-asset-pipeline:1.10.0"
compile ":jquery-ui:1.10.4"
// plugins needed at runtime but not for compilation
runtime ":hibernate4:4.3.5.5" // or
//runtime ":hibernate:3.6.10.17"
runtime ":database-migration:1.4.0"
runtime ":jquery:1.11.1"
// Uncomment these to enable additional asset-pipeline capabilities
//compile ":sass-asset-pipeline:1.9.0"
//compile ":less-asset-pipeline:1.10.0"
//compile ":coffee-asset-pipeline:1.8.0"
//compile ":handlebars-asset-pipeline:1.3.0.3"
}
}
I did some research and found out that I have to disable the forked mode as IDEA has problems with that. Therefor I disabled this feature in the BuildConfig.groovy with the grails.project.fork = false option.
Now I can't start the app via "run-app" because of the following exceptions:
2014-09-29 18:48:56,144 [localhost-startStop-1] ERROR pool.ConnectionPool - Unable to create initial connections of pool.
Message: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
Line | Method
->> 1094 | createSQLException in com.mysql.jdbc.SQLError
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 997 | createSQLException in ''
| 983 | createSQLException in ''
| 928 | createSQLException in ''
| 959 | createSQLException in ''
| 949 | createSQLException in ''
| 432 | handleNewInstance in com.mysql.jdbc.Util
| 419 | getInstance in com.mysql.jdbc.ConnectionImpl
| 344 | connect . . . . . in com.mysql.jdbc.NonRegisteringDriver
| 334 | innerRun in java.util.concurrent.FutureTask$Sync
| 166 | run . . . . . . . in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
Caused by NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
->> 7467 | realClose in com.mysql.jdbc.ResultSetImpl
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 923 | close in ''
| 801 | convertShowWarningsToSQLWarnings in com.mysql.jdbc.SQLError
| 4445 | scanForAndThrowDataTruncation in com.mysql.jdbc.MysqlIO
| 2923 | sqlQueryDirect . . in ''
| 2820 | execSQL in com.mysql.jdbc.ConnectionImpl
| 2769 | execSQL . . . . . in ''
| 1569 | executeQuery in com.mysql.jdbc.StatementImpl
| 4210 | loadServerVariables in com.mysql.jdbc.ConnectionImpl
| 3604 | initializePropsFromServer in ''
| 2542 | connectOneTryOnly in ''
| 2309 | createNewIO in ''
| 834 | <init> . . . . . . in ''
| 46 | <init> in com.mysql.jdbc.JDBC4Connection
| 408 | handleNewInstance in com.mysql.jdbc.Util
| 419 | getInstance in com.mysql.jdbc.ConnectionImpl
| 344 | connect . . . . . in com.mysql.jdbc.NonRegisteringDriver
| 334 | innerRun in java.util.concurrent.FutureTask$Sync
| 166 | run . . . . . . . in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
Error |
2014-09-29 18:48:56,203 [localhost-startStop-1] ERROR pool.ConnectionPool - Unable to create initial connections of pool.
Message: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
Line | Method
->> 1094 | createSQLException in com.mysql.jdbc.SQLError
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 997 | createSQLException in ''
| 983 | createSQLException in ''
| 928 | createSQLException in ''
| 959 | createSQLException in ''
| 949 | createSQLException in ''
| 432 | handleNewInstance in com.mysql.jdbc.Util
| 419 | getInstance in com.mysql.jdbc.ConnectionImpl
| 344 | connect . . . . . in com.mysql.jdbc.NonRegisteringDriver
| 334 | innerRun in java.util.concurrent.FutureTask$Sync
| 166 | run . . . . . . . in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
Caused by NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
->> 7467 | realClose in com.mysql.jdbc.ResultSetImpl
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 923 | close in ''
| 801 | convertShowWarningsToSQLWarnings in com.mysql.jdbc.SQLError
| 4445 | scanForAndThrowDataTruncation in com.mysql.jdbc.MysqlIO
| 2923 | sqlQueryDirect . . in ''
| 2820 | execSQL in com.mysql.jdbc.ConnectionImpl
| 2769 | execSQL . . . . . in ''
| 1569 | executeQuery in com.mysql.jdbc.StatementImpl
| 4210 | loadServerVariables in com.mysql.jdbc.ConnectionImpl
| 3604 | initializePropsFromServer in ''
| 2542 | connectOneTryOnly in ''
| 2309 | createNewIO in ''
| 834 | <init> . . . . . . in ''
| 46 | <init> in com.mysql.jdbc.JDBC4Connection
| 408 | handleNewInstance in com.mysql.jdbc.Util
| 419 | getInstance in com.mysql.jdbc.ConnectionImpl
| 344 | connect . . . . . in com.mysql.jdbc.NonRegisteringDriver
| 334 | innerRun in java.util.concurrent.FutureTask$Sync
| 166 | run . . . . . . . in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
Error |
2014-09-29 18:48:56,251 [localhost-startStop-1] ERROR pool.ConnectionPool - Unable to create initial connections of pool.
Message: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
Line | Method
->> 1094 | createSQLException in com.mysql.jdbc.SQLError
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 997 | createSQLException in ''
| 983 | createSQLException in ''
| 928 | createSQLException in ''
| 959 | createSQLException in ''
| 949 | createSQLException in ''
| 432 | handleNewInstance in com.mysql.jdbc.Util
| 419 | getInstance in com.mysql.jdbc.ConnectionImpl
| 344 | connect . . . . . in com.mysql.jdbc.NonRegisteringDriver
| 334 | innerRun in java.util.concurrent.FutureTask$Sync
| 166 | run . . . . . . . in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
Caused by NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
->> 7467 | realClose in com.mysql.jdbc.ResultSetImpl
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 923 | close in ''
| 801 | convertShowWarningsToSQLWarnings in com.mysql.jdbc.SQLError
| 4445 | scanForAndThrowDataTruncation in com.mysql.jdbc.MysqlIO
| 2923 | sqlQueryDirect . . in ''
| 2820 | execSQL in com.mysql.jdbc.ConnectionImpl
| 2769 | execSQL . . . . . in ''
| 1569 | executeQuery in com.mysql.jdbc.StatementImpl
| 4210 | loadServerVariables in com.mysql.jdbc.ConnectionImpl
| 3604 | initializePropsFromServer in ''
| 2542 | connectOneTryOnly in ''
| 2309 | createNewIO in ''
| 834 | <init> . . . . . . in ''
| 46 | <init> in com.mysql.jdbc.JDBC4Connection
| 408 | handleNewInstance in com.mysql.jdbc.Util
| 419 | getInstance in com.mysql.jdbc.ConnectionImpl
| 344 | connect . . . . . in com.mysql.jdbc.NonRegisteringDriver
| 334 | innerRun in java.util.concurrent.FutureTask$Sync
| 166 | run . . . . . . . in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
Error |
2014-09-29 18:48:56,269 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing the application: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
Message: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
Line | Method
->> 334 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 166 | run in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
->> 334 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 166 | run in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' while setting bean property 'hibernateProperties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
->> 334 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 166 | run in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetector' while setting bean property 'properties' with key [hibernate.dialect]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
->> 334 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 166 | run in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
Caused by BeanCreationException: Error creating bean with name 'dialectDetector': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
->> 334 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 166 | run in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
Caused by MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
->> 334 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 166 | run in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
Caused by SQLException: java.lang.NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
->> 1094 | createSQLException in com.mysql.jdbc.SQLError
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 997 | createSQLException in ''
| 983 | createSQLException in ''
| 928 | createSQLException in ''
| 959 | createSQLException in ''
| 949 | createSQLException in ''
| 432 | handleNewInstance in com.mysql.jdbc.Util
| 419 | getInstance in com.mysql.jdbc.ConnectionImpl
| 344 | connect . in com.mysql.jdbc.NonRegisteringDriver
| 334 | innerRun in java.util.concurrent.FutureTask$Sync
| 166 | run . . . in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
Caused by NoSuchMethodError: com.mysql.jdbc.StatementImpl.removeOpenResultSet(Ljava/sql/ResultSet;)V
->> 7467 | realClose in com.mysql.jdbc.ResultSetImpl
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 923 | close in ''
| 801 | convertShowWarningsToSQLWarnings in com.mysql.jdbc.SQLError
| 4445 | scanForAndThrowDataTruncation in com.mysql.jdbc.MysqlIO
| 2923 | sqlQueryDirect in ''
| 2820 | execSQL in com.mysql.jdbc.ConnectionImpl
| 2769 | execSQL . in ''
| 1569 | executeQuery in com.mysql.jdbc.StatementImpl
| 4210 | loadServerVariables in com.mysql.jdbc.ConnectionImpl
| 3604 | initializePropsFromServer in ''
| 2542 | connectOneTryOnly in ''
| 2309 | createNewIO in ''
| 834 | <init> . in ''
| 46 | <init> in com.mysql.jdbc.JDBC4Connection
| 408 | handleNewInstance in com.mysql.jdbc.Util
| 419 | getInstance in com.mysql.jdbc.ConnectionImpl
| 344 | connect . in com.mysql.jdbc.NonRegisteringDriver
| 334 | innerRun in java.util.concurrent.FutureTask$Sync
| 166 | run . . . in java.util.concurrent.FutureTask
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
My DataSource.groovy:
dataSource {
pooled = true
jmxExport = true
driverClassName = "com.mysql.jdbc.Driver"
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
// cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
singleSession = true // configure OSIV singleSession mode
flush.mode = 'manual' // OSIV session flush mode outside of transactional context
reload = false
}
// environment specific settings
environments {
development {
dataSource {
pooled = true
dbCreate = "update"
url = "jdbc:mysql://localhost:3306/xxx?autoreconnect=true"
driverClassName = "com.mysql.jdbc.Driver"
properties {
// See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
jmxEnabled = true
initialSize = 5
maxActive = 50
minIdle = 5
maxIdle = 25
maxWait = 10000
maxAge = 10 * 60000
timeBetweenEvictionRunsMillis = 5000
minEvictableIdleTimeMillis = 60000
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
testOnBorrow = true
testWhileIdle = true
testOnReturn = false
jdbcInterceptors = "ConnectionState"
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
}
username = ""
password = ""
}
}
test {
pooled = true
dbCreate = "update"
url = "jdbc:mysql://localhost:3306/xxx?autoreconnect=true"
driverClassName = "com.mysql.jdbc.Driver"
properties {
// See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
jmxEnabled = true
initialSize = 5
maxActive = 50
minIdle = 5
maxIdle = 25
maxWait = 10000
maxAge = 10 * 60000
timeBetweenEvictionRunsMillis = 5000
minEvictableIdleTimeMillis = 60000
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
testOnBorrow = true
testWhileIdle = true
testOnReturn = false
jdbcInterceptors = "ConnectionState"
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
}
username = ""
password = ""
}
production {
dataSource {
pooled = true
dbCreate = "update"
url = "jdbc:mysql://localhost:3306/xxx?autoreconnect=true"
driverClassName = "com.mysql.jdbc.Driver"
properties {
// See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
jmxEnabled = true
initialSize = 5
maxActive = 50
minIdle = 5
maxIdle = 25
maxWait = 10000
maxAge = 10 * 60000
timeBetweenEvictionRunsMillis = 5000
minEvictableIdleTimeMillis = 60000
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
testOnBorrow = true
testWhileIdle = true
testOnReturn = false
jdbcInterceptors = "ConnectionState"
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
}
username = ""
password = ""
}
}
}
Any idea how I could solve these problems?
Please take a look at this post: Grails 2.4.3 fails to reload controller or service
If it doesn´t help please provide your BuildConfig.groovy
I am trying to do the next select:
ArrayList<Personal> personalAuxList = new ArrayList<Personal>()
def campaigns = Campaign.findAllByEntidad(entidadInstance,[sort: "fechaFin", order: "desc"])
//Here a declare a DetachedCriteria using where method of domain class
def notificacionesQuery = Notificacion.where {
orden.linea.propuesta.campaign in campaigns
}
//For each persona from a search result done before
for(Personal person : result.results){
if(!personalAuxList.contains(person)){
//I add a condition to query creating new one
def notisOfPersonalQuery = notificacionesQuery.where {
personal == person
}
//Fail in this line when i list the result
def notificaciones = notisOfPersonalQuery.list()
notificaciones = notificaciones.sort{it.orden.linea.fin}.reverse()
notisOfPersonal.put(person.id, notificaciones.empty ? null : notificaciones.first())
personalAuxList.add(person)
}
}
That works fine on local, but when i upload the war, start failing in the server:
Class: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException
Message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') and this_.personal_id=6616' at line 1
Trace:
Line | Method
->> 411 | handleNewInstance in com.mysql.jdbc.Util
| 386 | getInstance in ''
| 1052 | createSQLException . in com.mysql.jdbc.SQLError
| 4098 | checkErrorPacket in com.mysql.jdbc.MysqlIO
| 4030 | checkErrorPacket . . in ''
| 2490 | sendCommand in ''
| 2651 | sqlQueryDirect . . . in ''
| 2677 | execSQL in com.mysql.jdbc.ConnectionImpl
| 2134 | executeInternal . . in com.mysql.jdbc.PreparedStatement
| 2300 | executeQuery in ''
| 97 | executeQuery . . . . in org.apache.commons.dbcp.DelegatingPreparedStatement
| 671 | doCall in grails.gorm.DetachedCriteria$_list_closure2
| 934 | doCall . . . . . . . in grails.gorm.DetachedCriteria$_withPopulatedQuery_closure9
| 669 | doCall in org.grails.datastore.gorm.GormStaticApi$_withDatastoreSession_closure20
| 302 | execute . . . . . . in org.grails.datastore.mapping.core.DatastoreUtils
| 34 | execute in org.grails.datastore.gorm.AbstractDatastoreApi
| 668 | withDatastoreSession in org.grails.datastore.gorm.GormStaticApi
| 916 | withPopulatedQuery in grails.gorm.DetachedCriteria
| 667 | list . . . . . . . . in ''
| 666 | list in ''
| 301 | search . . . . . . . in com.publidirecta.PersonalController
^ 722 | run in java.lang.Thread
I solve it finally, on local i got campaigns in the DDBB but on real server no, so i change the code to add a condition if there's no campaigns:
ArrayList<Personal> personalAuxList = new ArrayList<Personal>()
def campaigns = Campaign.findAllByEntidad(entidadInstance,[sort: "fechaFin", order: "desc"])
if (campaigns != null && campaigns.size() > 0) {
def notificacionesQuery = Notificacion.where {
orden.linea.propuesta.campaign in campaigns
}
for(Personal person : result.results){
if(!personalAuxList.contains(person)){
def notisOfPersonalQuery = notificacionesQuery.where {
personal == person
}
def notificaciones = notisOfPersonalQuery.list()
notificaciones = notificaciones.sort{it.orden.linea.fin}.reverse()
notisOfPersonal.put(person.id, notificaciones.empty ? null : notificaciones.first())
personalAuxList.add(person)
}
}
}
I have mysql table named anto2. Which has only one column name of varchar 100. I tried to map this table in grails domain class :
class Anto {
String grailsName
static constraints = {
}
static mapping = {
table 'anto2'
grailsName column: 'name'
}
}
After I did run-app I can see my table have been added with two more columns :
+---------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| name | varchar(100) | YES | | NULL | |
| id | bigint(20) | NO | | NULL | |
| version | bigint(20) | NO | | NULL | |
+---------+--------------+------+-----+---------+-------+
I generated static view and controller for this Domain class and when I tried to save it , I get an error in my save() method (which is generated using generate-all command). The error is as follows :
2012-07-09 23:05:26,391 [http-bio-8080-exec-2] ERROR errors.GrailsExceptionResolver - SQLException occurred when processing request: [POST] /mysql/anto/save - parameters:
create: Create
Field 'id' doesn't have a default value. Stacktrace follows:
Message: Field 'id' doesn't have a default value
Line | Method
->> 1073 | createSQLException in com.mysql.jdbc.SQLError
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 3597 | checkErrorPacket in com.mysql.jdbc.MysqlIO
| 3529 | checkErrorPacket . in ''
| 1990 | sendCommand in ''
| 2151 | sqlQueryDirect . . in ''
| 2625 | execSQL in com.mysql.jdbc.ConnectionImpl
| 2119 | executeInternal . in com.mysql.jdbc.PreparedStatement
| 2415 | executeUpdate in ''
| 2333 | executeUpdate . . in ''
| 2318 | executeUpdate in ''
| 105 | executeUpdate . . in org.apache.commons.dbcp.DelegatingPreparedStatement
| 25 | save in mnm.AntoController
| 1110 | runWorker . . . . in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . . . . . in java.lang.Thread
Why does this happen? Where I went wrong?
If you don't specify your kind of id generator, GORM will use the native strategy of your database.If you're using mysql as db, it will create your ids using IDENTITY strategy to generate them. This strategy requires to have an auto increment on your id column.
Although I think defining a strategy is better. You can use the SEQUENCE strategy:
id column:'id_anto2', generator:'sequence', params:[sequence:'tab_anto2_seq']
and then create a sequence with that same name in your database (so you don't have to use the one Hibernate creates for you automatically). It's very easy and works like a charm.
Also, to discard the version field, insert version false in your mapping block. So, it would be like:
static mapping = {
table 'anto2'
id column: 'id_anto2', generator: 'sequence', params: [sequence:'tab_anto2_seq']
grailsName column: 'name'
version false
}
It looks like you are missing id mapping. Try adding an id reference to your static mapping closure. Also, if this is an existing database you might want to set the version to false or grails might try to alter the table with a version column, depending on how you have datasource.groovy set up.
table 'anto2'
version false
id column:'anto2_ID'
grailsName column: 'name'