Field values rendered null when using HTTP GET call in grails - grails

This is domain class of Person :
package com.sample
class Person {
String id
String name
Integer age
Address address
static hasMany = [pets:Pet, alias: String, aliases : Alias]
static mapWith = "mongo"
static constraints = {
address nullable:true
pets nullable :true
}
}
This is the domain class of Address :
package com.sample
class Address {
String address
static mapWith = "mongo"
static constraints = {
address maxSize: 1000
}
}
This is ShowPerson method in PersonController:
def showPerson(String name,String age){
if(Person.findByAgeAndName(age,name) != null) {
render Person.findByAgeAndName(age,name) as JSON
}
else {
def addobj = new Address(address: "kondapur")
addobj.save(flush:true)
def pet1 = new Pet(name : "Dog", breed : "A")
pet1.save(flush:true)
def alias1 = "ALIAS1"
def alias2 = "ALIAS2"
def list = ["A"]
def aliases1 = new Alias(aliasname : [list])
aliases1.save(flush:true)
def person = new Person(name : name, age : age, address : addobj, pets : [pet1], alias : [alias1, alias2], aliases : [aliases1])
person.save()
render person as JSON
}
}
Initially there are no persons in DB(which impliesPerson.findByAgeAndName(age,name) == null) Hence it creates a new object and saves it in database). So when I click on the url
> http://localhost:8080/TestJson/showPerson/sample/23
The output now is :
Now when I reclick on the same url (implies Person.findByAgeAndName(age,name) != null) Hence it gets from the database):
The output now is :
In database the address is saved as :
In database the person is saved as :
Can someone tell me how can I get the address (encircled in red) as not null and get the corresponding value when I try to get a saved object from database (i.e in this case kondapur and not null)

Grails JSON marshaller by default doesn't add nested classes, you have to add one line of code:
def showPerson(String name,String age){
JSON.use('deep')// <============================== Add this line
if(Person.findByAgeAndName(age,name) != null) {
render Person.findByAgeAndName(age,name) as JSON
}
else {
def addobj = new Address(address: "kondapur")
addobj.save(flush:true)
def pet1 = new Pet(name : "Dog", breed : "A")
pet1.save(flush:true)
def alias1 = "ALIAS1"
def alias2 = "ALIAS2"
def list = ["A"]
def aliases1 = new Alias(aliasname : [list])
aliases1.save(flush:true)
def person = new Person(name : name, age : age, address : addobj, pets : [pet1], alias : [alias1, alias2], aliases : [aliases1])
person.save()
render person as JSON
}
}

Related

Grails search from one to many is not working

Here are my domain class,
class Company {
String name
static hasMany = [groups:CompanyGroup]
}
class CompanyGroup{
String name
static belongsTo = [company:Company]
}
I receive params that contain name of CompanyGroup and I want to get the result of company that have the CompanyGroup found.
I did like this,
def groupList = account.companies.groups.flatten()
def groupResult = groupList.findAll{
it.name ==~ /(?i).*${params.keyword}.*/
}
I got the Companygroups that have name from params.key from above code. So I want to render company list that have these group like this,
def com = Company.withCriteria{
eq("groups", groupList)
}
render [companies : com]
It doesn't work!
def com = Company.withCriteria{
inList("groups", groupList)
}

Saving related entity in grails

I have a problem with saving form values from two domain classes
One class is
class Ip {
String inetAddress
String dns
String os
String toString(){
"${inetAddress}"
}
Hoster hoster
static constraints = {
....
and the second one is just
class Hoster {
static HOSTER_OPTIONS = ["Name1", "Name2", "Name3"]
String name;
String toString(){
"${name}"
}
List ips = new ArrayList()
static hasMany = [ips : Ip]
static constraints = {
name(unique: true, blank: false, inList: HOSTER_OPTIONS)
}
I have a Controller where I handle the data from a form
def systems = new Ip()
systems.inetAddress = params.ip
systems.dns = params.dns
systems.os = params.os
systems.hoster.name = params.hoster
def result = systems.save(flush: true, failOnError: true)
But I didn't get it managed that the data is saved.
You're not associating correctly your domain classes in the controller:
systems.hoster.name = params.hoster
Instead of setting the name, you need to set the instance that exists in the database:
systems.hoster = Hoster.findByName(params.hoster)

Equals object criteria query

If I have two domain classes like this:
class Company{
string Name
string address
}
class User {
string firstName
string lastName
Company company
}
How can I get all the users from company named Google using criteria query? Something like this:
def company = Company.findByName("Google")
def c = User.createCriteria()
def usersByCompany = c.list {
eq("company", company)
}
You can declare a block inside your closure to filter any field in the Company:
def usersOfGoogle = User.createCriteria().list() {
company {
eq('name', 'Google')
}
}
I just don't remember if it works only for relationships (belongsTo & hasMany), maybe you will need to change your domain class:
class User {
static belongsTo = [company : Company]
}

Deserialize a JSON object with support for embedded associations

Is there an easy way to deserialize a JSON string to a domain class with support of embedded association; belongsTo and hasMany
{
name: "Customer",
contact: {
name: "Contact"
}
}
class Customer {
name
Contact contact
}
class Contact {
String name
static belongsTo = [customer:Customer]
}
in my controller I would like to do the following
def save() {
def customer = new Customer(request.JSON)
customer.save();
}
Now i'm forced to do
def save() {
def contact = new Contact(request.JSON.contact);
def customer = new Customer(request.JSON);
customer.contact = contact;
customer.save();
}
Have you tried using JsonSlurper?
Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"
Ref: http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html
you can try this
Test test
def result = new JsonSlurper().parseTest('yourString')
test = result
Try this will work.

How to save associated object in Grails?

I am a grails beginner.
i have a 2domain class
class Employee {
String name
String department
static constraints = {
}
public String toString() {
name
}
}
class Address {
String line1
String line2
Employee employee
static belongsTo = Employee
static constraints = {
}
}
where Address belongs to Employee .. so i have given belongsTo association.
My Employee/create.gsp page takes input for fields specified in Employee and Address.
so on creation of employee , address must be get save automatically .
so what could be the save action in EmployeeController
i have tried some thing like this but did not work.
def save = {
def employeeInstance = new Employee(params)
def addressInstance = new Address(params)
if (employeeInstance.save(flush: true)) {
flash.message = "${message(code: 'default.created.message', args: [message(code: 'employee.label', default: 'Employee'), employeeInstance.id])}"
redirect(action: "show", id: employeeInstance.id)
}
else {
render(view: "create", model: [employeeInstance: employeeInstance])
}
}
how to save this associated model ?
Here you have a one-to-one relationsip - add an address property to the Employee class.
class Employee {
String name
String department
Address address
public String toString() {
name
}
}
Change your belongsTo of the Address like this:
class Address {
String line1
String line2
static belongsTo = [employee: Employee]
}
Now you could create an Employee like this:
def employeeInstance = new Employee(params)
employeeInstance.address = new Address(params)
if (employeeInstance.save(flush: true)) {
// your logic
}
Read the docs (one-to-one relationship) for further informations.

Resources