simple grails GSON plugin usage - grails

I am trying to use this super good plugin:
https://github.com/robfletcher/grails-gson/blob/master/test/apps/gson-test/grails-app/controllers/grails/plugin/gson/test/AlbumController.groovy
because the default GRAILS JSON does not expand the related items.
However when I try it, it fails.
Now, when i do this, it works:
def levelJson() {
render ToolType.list(params) as JSON
}
This fails:
def levelJson() {
render ToolType.list(params) as GSON
}
Error:
ERROR errors.GrailsExceptionResolver - UnsupportedOperationException occurred when processing request: [GET] /authtools/toolType/levelJson
Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?. Stacktrace follows:
Message: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
Classes:
class Artist {
String name
static hasMany = [albums: Album]
}
class Album {
String title
static belongsTo = Artist
}

The solution as dmahapatro pointed out was to modify the data class belongsTo
Before (not working):
class Album {
String title
static belongsTo = Artist
}
After (working):
class Album {
String title
static belongsTo = [artist: Artist]
}

Related

grails - calling overriden getter in domain class

I'm using Grails 2.4.4. I've got domain class
class Purchase {
static hasMany = [dataList:DataByPeriod]
String name
Set<DataByPeriod> dataList
public Set<DataByPeriod> getDataList(){
dataList?.findAll { (!it.isDeleted) }
}
def getPeriodList(){
this.dataList?.period?.unique()?.sort{it.name}
}
}
and another two:
class DataByPeriod {
static belongsTo = [purchase:Purchase, period:Period]
Long value
}
class Period {
static hasMany = [dataList:DataByPeriod]
String name
}
Now I want to receive all periods for given purchaseInstance. If I do:
purchaseInstance?.dataList?.period?.unique()?.sort{it.name}
I'll get correct data (getter for dataList will be called and all records with isDeleted==true will be ignored
But if I I do:
purchaseInstance?.getPeriodList()
getter will not be called and all records will be shown?
Why does this happens? Why I even cannot change my 'getPeriodList()` method to:
def getPeriodList(){
this.getDataList()?.period?.unique()?.sort{it.name}
}
It says that 'there is no method getDataList() for class Purchase'.

Creating Domain Relationships in Grails returns unable to resolve class error

Good day to all. I am very new in using grails and I have followed several tutorials for beginners using grails until I come up in creating domain relationships. However, I got stuck with this problem right now. I have 3 domain classes namely, todo, category and user. And as I defined their relationships, it returns me an error saying unable to resolve class. Please see my codes below. Please help. Thank you so much.
Todo.groovy Class
package todoScaff
class Todo {
String name
String note
Date createDate
Date dueDate
Date completedDate
String priority
String status
User owner
Category category
static belongsTo = [User, Category]
static constraints = {
name(blank:false)
createDate()
priority()
status()
note(maxsize:1000, nullable:true)
completedDate(nullable:true)
dueDate(nullable:true)
}
String toString() {
name
}
}
Category.groovy Class
package categoryScaff
class Category {
String name
String description
User user
static belongsTo = User
static hasMany = [todos: Todo]
static constraints = {
name(blank:false)
}
String toString(){
name
}
}
User.groovy Class
package userScaff
class User {
String userName
String fname
String lname
static hasMany = [todos: Todo, categories: Category]
static constraints = {
userName(blank:false, unique:true)
fname(blank:false)
lname(blank:false)
}
String toString(){
"$lname, $fname"
}
}
Since you've placed your domain classes in different packages, you must import the classes at the head of the file.
package categoryScaff
import todoScaff.Todo
import userScaff.User
class Category {
The same needs to happen in your other domain classes that reference classes outside the current package.

MongoDB Collection Access

I'm using MongoDB exclusively with a Grails REST app and the domain shown below. This respond call fails:
#Secured(['permitAll'])
def index() {
respond Person.list()
}
with the error
ERROR errors.GrailsExceptionResolver - IllegalAccessException occurred when processing request: [GET] /teesheet/person
Class org.codehaus.groovy.grails.web.converters.marshaller.json.GroovyBeanMarshaller can not access a member of class java.util.Collections$UnmodifiableCollection with modifiers "public". Stacktrace follows:
Message: Class org.codehaus.groovy.grails.web.converters.marshaller.json.GroovyBeanMarshaller can not access a member of class java.util.Collections$UnmodifiableCollection with modifiers "public"
Attempting to convert the collection to JSON also fails with the same error.
def personList = Person.list() as JSON
The low level API works.
package com.tworks.teesheet
import grails.rest.Resource
class Person {
String name
String firstName
String lastName
String email
User userPerson
TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles")
Date dateCreated = new Date()
Date dateModified = new Date()
}
Assuming you're using Mongo for Grails plugin, you need #Entity for domain classes...
import grails.persistence.Entity
#Entity
class Person {
static mapWith = "mongo"
String name
String firstName
String lastName
String email
}
I added mapWith="mongo" since I wasn't sure if you're using the hibernate plugin alongside the mongo plugin; if you're not, remove hibernate, otherwise, it may interfere.
I'm currently using the low level calls to iterate using the cursor but it seems like the respond Person.list() should work. This code is working:
def cursor = Person.collection.find()
def items = []
try {
while (cursor.hasNext()) {
items << com.mongodb.util.JSON.serialize(cursor.next())
}
} finally {
cursor.close()
}
log.info("items: ${items}")
render items

How to use namedQueries in Grails 1.3.7 with object containing object?

I have these classes:
class Category {
Set usersLinked
def hasMany = [usersLinked:CategoryUserLink]
static namedQueries = {
getAuthorizedBusiness { auser ->
eq "business", true
usersLinked{
eq "user", auser
type{
eq "name", "Authorized"
}
}
}
}
}
class CategoryUserLink {
User user
CategoryType type
Category category
}
When I querying on it with a namedQuery or a createCriteria I receive an error:
Category.getAuthorizedBusiness(user).list()
No such property usersLinked
Why?
I receive this error message:
org.hibernate.QueryException: could not resolve property: userslinked of: lli.faqapp.domain.Category
at grails.orm.HibernateCriteriaBuilder.invokeMethod(HibernateCriteriaBuilder.java:1223)
at grails.orm.GormLabsHibernateCriteriaBuilder.super$3$invokeMethod(GormLabsHibernateCriteriaBuilder.groovy)
at grails.orm.GormLabsHibernateCriteriaBuilder.methodMissing(GormLabsHibernateCriteriaBuilder.groovy:65)
at lli.faqapp.domain.Category$__clinit__closure3_closure4.doCall(Category.groovy:84)
at grails.orm.HibernateCriteriaBuilder.invokeClosureNode(HibernateCriteriaBuilder.java:1367)
at grails.orm.HibernateCriteriaBuilder.invokeMethod(HibernateCriteriaBuilder.java:1117)
at GormLabsGrailsPlugin$_registerCriteria_closure23_closure38.doCall(GormLabsGrailsPlugin.groovy:255)
at lli.faqapp.domain.tests.CategoryTests.testSearchOnCategories(CategoryTests.groovy:39)
And after removing the plugin GormLabs, I start the integration test and I receive this message:
org.hibernate.QueryException: could not resolve property: userslinked of: lli.faqapp.domain.Category
at grails.orm.HibernateCriteriaBuilder.invokeMethod(HibernateCriteriaBuilder.java:1223)
at lli.faqapp.domain.Category$__clinit__closure3_closure4.doCall(Category.groovy:84)
at grails.orm.HibernateCriteriaBuilder.invokeClosureNode(HibernateCriteriaBuilder.java:1367)
at grails.orm.HibernateCriteriaBuilder.invokeMethod(HibernateCriteriaBuilder.java:1117)
at lli.faqapp.domain.tests.CategoryTests.testSearchOnCategories(CategoryTests.groovy:39)
hasMany must be static - it's a property of the Class, not a specific instance. The Set usersLinked that it generates is instance-specific, but the hasMany declaration is for the Class.

Grails many-to-many relationship

I'm trying to do a many-to-many relationship on Grails 1.3.4 and I'm getting this exception:
Caused by: org.codehaus.groovy.grails.exceptions.GrailsDomainException: No owner defined between domain
classes [class gblog.Post] and [class gblog.Comentario] in a many-to-many relationship.
Example: static belongsTo = gblog.Comentario
The code for Comentario is:
package gblog
class Comentario {
static constraints = {
}
String conteudo
Date data
static belongsTo = [post:Post, autor:Usuario]
static hasMany = [posts:Post]
}
The code for Post is:
package gblog
class Post {
static constraints = {
}
String titulo
String conteudo
String palavrasChave
Date data
static belongsTo = [categoria:Categoria, autor:Usuario]
static hasMany = [comentarios:Comentario]
}
Thanks everybody!
I think Grails is getting confused here:
static belongsTo = [post:Post, autor: Usuario]
static hasMany = [posts:Post]
You might want to diagram how all of the classes are interacting, because I'm thinking that this is a little off.

Resources