Grails Entity Relationship - grails

I have the following entities Alert and Location in Grails. But I cant seem to add the location to the alert_location table. The error is missing method exception. Pls help.
class Alerts {
static hasMany = [locations:Locations,users:Users]
Date alertDateTime
String pest
String crop
static constraints = {
alertDateTime (blank:false)
pest (blank:false)
crop (blank:false)
}
class Locations {
static hasMany = [ farms:Farms, reports:Reports, reportMessages:ReportMessages]
String locationName
String locationXY
static constraints = {
locationName (blank:false)
locationXY (blank:false, unique:true)
}
}
In my code,
Locations loc = new Locations();
loc.locationName = 'a'
loc.locationXY = 'aa'
loc.save()
Alerts a = new Alerts()
Date d = new Date()
a.alertDateTime =d
a.crop ="o"
a.pest ="c"
//a.save()
println loc.locationName
loc.addToAlerts(a)
a.save()

Try a.addToLocations(loc) instead because you are using a.save(). Otherwise do loc.save()

Related

Is it possible to add setter for inner(nested) fields in dart?

In dart we can execute some code when value of field is changed using something like
class Name{
String fname;
String lname;
}
class Person extends ChangeNotifier{
Name _name = Name();
set name(Name n){
notifyListeners();
_name = n;
}
get name=>_name;
}
//inside main()
Person p = Person();
p.name = Name();
I want to be able to perform similar action while setting inner fields. Such as while doing
p.name.fname ="FooBar";
But I want to be able to do it from Person class.
Because I am extending ChangeNotifier in Person class. And I want to call
notifyListeners()
that is not accessible in Name class. This is best I've come up with
Name newName = Name(p.name); //copy constructor
newName.fname = "Foo Bar";
p.name = newName;
Is there a better way?
What you can do depends on how you can constrain the API.
If Name objects are routinely being created by third-party code and passed around, and are expected to retain their identity when stored in a Person object, then here isn't much you can do. So I wouldn't design the Person object that way.
Instead I'd say that the Name object of a Person object is linked to that, and setting the name of a Person is the same as setting both name parts.
Example:
class Person {
_PersonName _name;
Person(...) : ... {
_name = _PersonName(this);
}
...
void set name(Name name) {
_name.fname = name.fname;
_name.lname = name.lname;
notifyListeners();
}
Name get name => _name;
}
class _PersonName extends Name {
final Person _owner;
_PersonName(this._owner);
void set fname(String fname) {
super.fname = fname;
_owner.notifyListeners();
}
void set lname(String lname) {
super.lname = lname;
_owner.notifyListeners();
}
}
That has the disadvantage that the extracted _PersonName is forever linked to the Person object, even if you try to write a different Name object.
Another option is to create a new _PersonName on every store a new name object, and detach the old object from the Person at that point:
class Person {
_PersonName _name = _PersonName;
Person(...) : ... {
_name = _PersonName(this, null, null);
}
void set name(Name name) {
_name.owner = null;
_name = _PersonName(this, name.fname, name.lname);
notifyListeners();
}
Name get name => _name;
}
class _PersonName extends Name {
Person _owner;
_PersonName(this._owner, String fname, String lname) {
super.fname = fname;
super.lname = lname;
}
void set fname(String fname) {
super.fname = fname;
owner?.notifyListeners();
}
void set lname(String lname) {
super.lname = lname;
owner?.notifyListeners();
}
}
This approach behaves mostly like the plain storing of name objects, except that if you do:
var p = Person();
var n = Name();
p.name = n;
print(identical(n, p.name)); // false?
you don't preserve the identity of the Name object stored into the Person object.
There is no way to do so, and also change the behavior of setting strings directly on the name using person.name.fname = ..., so something has to be sacrificed.

How to retrieve all instance in grails database

These are my domain class
GameCategory.groovy
class GameCategory {
String categoryName
String icon
String toString(){
"${categoryName}"
}
static hasMany = [ list:GameList]
static constraints = {
}
Game.groovy
class Game {
String gameTitle
float gamePrice
String gameDescription
Date releaseDate
float rating
int numberOfRaters
int numberOfReviews
String toString(){
"${gameTitle}"
}
static hasMany = [list : GameList ]
static constraints = {
}
GameList.groovy
class GameList {
static belongsTo = [game : Game , category : GameCategory]
static constraints = {
}
My question is, how do I retrieve all instance of a game given a category as parameter I'm having trouble understanding the hasMany and belongsTo in grails
GameList.findAllByCategory(myCategory).collect{it.game}
You could make it more complicated by using createCriteria but then you have to join with an alias and the code will become more complicated.

Request via dynamic finders in Grails

I've three domain classess:
class Cafee {
String cafeeName
static hasMany = [halls: HallsZones]
static constraints = {
halls nullable: true
}
}
class HallsZones {
String hallName
static scaffold = true
static hasMany = [table : TablePlacesInfo]
static belongsTo = [cafee : Cafee]
static constraints = {
table nullable: true
cafee nullable: true
}
}
class TablePlacesInfo {
int placesInTableAmount
int tableAmount
int tableForReservationAmount
int placeCost
String currencyType
static scaffold = true
static belongsTo = [hall: HallsZones]
static constraints = {
hall nullable: true
}
}
As you can see, classess are connected with each other as via chain:
Cafee-(hasMany)->HallsZones-(hasMany)->TablePlacesInfo.
I want to get TablePlaces info, which has HallsZones as parent which in turn has a Cafee as parent.
I know how to search by parent, for example:
def table = TablePlacesInfo.findWhere(hall : params['hallsAvailable'], placesInTableAmount : Integer.parseInt(params['tablePlacesAvailable']))
But how to search by grandparent too?
Using where query:
TablePlacesInfo.where {
hall {
cafee {
// criteria matching grand parent
id == 1L // for example
}
}
}.list()
Using Criteria:
TablePlacesInfo.withCriteria {
hall {
cafee {
// criteria matching grand parent
idEq 1L // for example
}
}
}
Using hql:
TablePlacesInfo.executeQuery(
"""select tpi from TablePlacesInfo as tpi
inner join tpi.hall as hall
inner join hall.cafee as caf
where caf.id = 1"""
)
Choosing a DetachedCriteria or where would be a sound approach instead of dynamic finders.

Derived field in GORM utilizing mapped owner's fields

I'm trying to figure out how to make a derived boolean field in my domain class. The boolean field is derived from comparison to the mapped owner's values. Is this possible in GORM? I've tried it quite a few different ways and I keep getting various SQL errors. My domain classes are below:
class Reading {
float readingValue
Date dateCreated
boolean alarmedState
static constraints = {
readingValue(nullable: false)
}
static belongsTo = [sensor : Sensor]
static mapping = {
autoTimestamp true
sort "dateCreated"
alarmedState formula: "(READING_VALUE < SENSOR.ALARM_IF_LESS) || (READING_VALUE > SENSOR.ALARM_IF_GREATER)"
}
}
class Sensor {
String description
String location
SensorType typeEnum
double alarmIfGreater
double alarmIfLess
static hasMany = [readings : Reading]
static constraints = {
alarmIfGreater(nullable: true)
alarmIfLess(nullable: true)
description(blank: false)
location(blank: false)
typeEnum(blank: false)
}
}
The transients property might do what you want. E.g.
class Reading {
float readingValue
Date dateCreated
static constraints = {
readingValue(nullable: false)
}
static belongsTo = [sensor : Sensor]
static transients = ['alarmedState']
static mapping = {
autoTimestamp true
sort "dateCreated"
//alarmedState formula: "(READING_VALUE < SENSOR.ALARM_IF_LESS) || (READING_VALUE > SENSOR.ALARM_IF_GREATER)"
}
Boolean getAlarmedState() {
( readingValue < sensor.alarmIfLess || readingValue > sensor.alarmIfGreater )
}
}
I've not tested this code but it might get you on the right track...

grails 2.3.1 Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

I am getting the following error when I tried to create a new Employee in static scaffold:
Error 500: Internal Server Error
URI
/file-tracker/employee/save Class
org.hibernate.StaleStateException Message
Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
Around line 38 of
grails-app/controllers/org/simpragma/EmployeeController.groovy
Around line 191 of PageFragmentCachingFilter.java
What is wrong ?
package org.xyz
class Employee {
String name;
String department;
String role;
String userId;
String pw;
static mapping = {
table 'employee'
version false
id name: 'userId'
id generator: 'native'
}
static hasMany = [toAllocations: Allocation, fromAllocations: Allocation]
static mappedBy = [toAllocations: 'toEmployee', fromAllocations: 'fromEmployee']
static constraints = {
department nullable : true
role nullable : true
}
}
package org.xyz
class Allocation {
static hasOne = [file:File, toEmployee:Employee, fromEmployee:Employee, remark:Remark]
static mappedBy = [toEmployee: 'toAllocations', fromEmployee: 'fromAllocations' ]
static constraints = {
remark nullable: true
}
}
package org.xyz
class File {
String fileNumber;
Date requestedDate;
String requestedBy;
String priority;
Double budget;
String requestedByDepartment;
String subject;
static mapping = {
id name: 'fileNumber'
version false
id generator: 'native'
}
static hasMany = [allocations: Allocation]
static constraints = {
fileNumber nullable : true
priority nullable : true
budget nullable : true
}
}
package org.xyz
class Remark {
String remark;
Date remarkDate;
static belongsTo = [allocation: Allocation];
static constraints = {
}
}
In my case, for test purposes I was trying to assign my own id to object. I can't do that if id should be generated during save.

Resources