Why One-to-one relationship dosen't work? - grails

I'm trying to create a very simple relationship between two objects. Can anybody explain me why I can't find the Company object via findBy method?
class Company {
String name
String desc
City city
static constraints = {
city(unique: true)
}
}
class City {
String name
static constraints = {
}
}
class BootStrap {
def init = { servletContext ->
new City(name: 'Tokyo').save()
new City(name: 'New York').save()
new Company(name: 'company', city: City.findByName('New York')).save()
def c = Company.findByName('company') // Why c=null????!
}
def destroy = {
}
}

A field called desc conflicts with the database keyword for descending sort. Per default a field is nullable:false in Grails. So first rename that field to for example description and then provide one or mark that field as nullable:true in your constraints.
class BootStrap {
def init = { servletContext ->
new City(name: 'Tokyo').save()
new City(name: 'New York').save()
new Company(name: 'company', city: City.findByName("New York")).save()
assert Company.findByName('company') != null
}
}
Remember that you can always check for the errors that prevent Grails from saving your objects to the database easily:
def invalidCompany = new Company() // missing required name property
if (!invalidCompany.validate())
invalidCompany.errors.each { println it }

Related

Grails: HIbernate-filter - Adding filter on mapped class column

I want to use grails hibernate filter plugin to add a filter on of my domain class.
http://grails.org/plugin/hibernate-filter
Domain classes:
class Movie {
String name
String genre
String yearOfRelease
boolean deleted
}
class EditRequest {
String reason
String requester
Date requestDate
String status //can be 'PENDING', 'ONHOLD', OR 'COMPLETE'
static belongsTo = [
movie: Movie,
requester: User
]
}
There could be multiple edit request for a movie.
I have an API where I need to display all edit requests for all non-deleted movies.
How do I add hibernateFilter for non-deleted movies in my EditRequest domain class
I tried below in my EditRequest class, but non of them works.
1.
static hibernateFilters = {
deletedMovieFilter(condition:'deleted=false', default:true)
deletedMovieFilter(collection:'movie', default: true)
}
2.
static hibernateFilters = {
deletedMovieFilter(condition: 'deleted = false')
deletedMovieFilter(collection: 'movie', joinTable: true)
}

How to convert native sql to grails/gorm

Can I convert this to GRAILS/GORM. If yes, any help please.
select b.id, b.username, b.first_name, b.last_name
from tb_user_orgpermissions a
inner join tb_user b on a.username = b.username
where
(a.department_id = :dept_id)
and (a.agency_id = :agy_id)
To create the equivalent query as a gorm criteria query, the first thing you need is domain classes (with proper associations) for each table. As an example, here's some pseudo code:
class User {
String username
String firstName
String lastName
static hasOne = [permission: UserPermission]
}
class UserPermission {
Department department
Agency agency
}
class Department {}
class Agency {}
In this example User has a one-to-one association to UserPermission.
With something like this in place you can create a criteria query (with projections):
User.withCriteria {
projections {
property 'id'
property 'username'
property 'firstName'
property 'lastName'
}
permission {
department {
eq 'id', dept_id
}
agency {
eq 'id', agy_id
}
}
}

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]
}

Grails set default value of scaffolded dropdown box

Is it possible to set the default value for a generated (scaffolded) State dropdown box in Grails? I am hoping that this is something I can do within either the domain class or the controller class:
class State {
String name
String code
static mapping = { sort name: "asc" }
String toString() {
return this.name;
}
}
class Person implements Comparable {
String firstName
String lastName
State state
String toString() {
return this.lastName + ", " + this.firstName;
}
}
I have tried explicitly setting String name="Pennsylvania" and String code="PA" in the State domain class with no luck. I am bootstrapping the State data in Bootstrap.groovy:
def init = { servletContext ->
if (!State.count()) {
new State(name: "Alabama", code:"AL").save(failOnError: true)
new State(name: "Alaska", code:"AK").save(failOnError: true)
new State(name: "Arizona", code:"AZ").save(failOnError: true)
new State(name: "Arkansas", code:"AR").save(failOnError: true)
....
}
}
Updated:
PersonController.groovy:
def create() {
// [personInstance = new Person(params)]
def personInstance = new Person(params)
personInstance.state = new State("Pennsylvania", "PA")
[personInstance: personInstance]
}
State.groovy:
public State(String name, String code) {
this.name = name
this.code = code
}
If you're trying to set the default value of the state dropdown for the "new Person" page, then you would probably want to make the default value of Person's 'state' member be the 'Pennsylvania' state that you create in Bootstrap.
Actually, I think that a better way to do this would be to actually generate the PersonController, and then modify the 'create' closure to set the initial value of Person.state

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