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.
Related
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.
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...
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.
I have two tables, one of which (legacy table: A) has two fields that should serve as a composite foreign key and the other one (new table: B) should use a composite primary key for a each row:A has one row:B relationship. How do I describe these tables in terms of GORM?
So far I've been able to create a domain class that reflects the legacy table:A
class A {
...
//composite foreign key to link B class
String className;
String eventName;
B b; //instance of B to be related
static mapping = {
table 'a_table';
id column: 'id';
className column: 'class_name';
eventName column: 'event_name';
//b: ???
}
}
which works, but I can't create a new class:B and the relationship.
I tried to declare B as:
class B implements Serializable{
static auditable = true;
String name;
String className;
String eventName;
static mapping = {
//supposed to make a composite PK
id composite:[className, eventName]
}
}
but this won't compile with a
ERROR context.GrailsContextLoader - Error executing bootstraps: Error evaluating ORM mappings block for domain [com.package.B]: No such property: eventName for class: org.codehaus.groovy.grails.orm.hibernate.cfg.HibernateMappingBuilder
What I want is something like:
static mapping = {
...
b composite: [b.className:className, b.eventName:eventName]
//or whatever is the right way for this to be done.
}
for the A class to make GORM handle this relation.
Did you try to use attribute name instead of use attribute value ?
class B implements Serializable{
String name;
String className;
String eventName;
static mapping = {
//supposed to make a composite PK
id composite:['className', 'eventName']
}
}
And mapping in A :
class A {
static hasMany = [ b : B ]
}
No need to have className or eventName in A
The B class has to be declared Serializable and implements the equals and hashCode methods
import org.apache.commons.lang.builder.HashCodeBuilder
class B implements Serializable{
static auditable = true;
String name;
String className;
String eventName;
boolean equals(other) {
if (!(other instanceof B)) {
return false
}
other.className == className && other.eventName == eventName
}
int hashCode() {
def builder = new HashCodeBuilder()
builder.append className
builder.append eventName
builder.toHashCode()
}
static mapping = {
//supposed to make a composite PK
id composite:["className", "eventName"]
}
}
and the A class just must to have an attribute of the B class and the GORM make the composite foreign key
class A {
//composite foreign key to link B class
B b; //instance of B to be related
static mapping = {
table 'a_table';
id column: 'id';
}
}
it create two tables in the database
+--------------------------------------------------+
| A_TABLE |
+--------+-----------+--------------+--------------+
| id | version | b_className | b_eventName |
+--------+-----------+--------------+--------------+
--where the Primary key is "id" and the foreign key are "b_className and b_eventName"
+--------------------------------------------------+
| B |
+--------+-----------+--------------+--------------+
| name | version | className | eventName |
+--------+-----------+--------------+--------------+
--where the Primary key are "className and eventName"
if you what to change the name of the columns to other just add the clausule in the mapping statement
class A {
//composite foreign key to link B class
B b; //instance of B to be related
static mapping = {
table 'a_table';
id column: 'id';
columns {
b {
column name: "className"
column name: "eventName"
}
}
}
}
import org.apache.commons.lang.builder.HashCodeBuilder
class Person implements Serializable {
String firstName
String lastName
boolean equals(other) {
if (!(other instanceof Person)) {
return false
}
other.firstName == firstName && other.lastName == lastName
}
int hashCode() {
def builder = new HashCodeBuilder()
builder.append firstName
builder.append lastName
builder.toHashCode()
}
static mapping = {
id composite: ['firstName', 'lastName']
}
}
this is what you can find from official docs of grails,
http://grails.org/doc/latest/guide/GORM.html#compositePrimaryKeys
just blindly follow this and your problem will be solved. for explanation refer above link
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()