Grails additional columns in table or list - grails

I'm trying for several days to receive a list from my Data. The Domain looks like this:
class Alpha {
String a
String b
etc.
static hasMany = [beta:Beta]
}
class Beta {
String a
Integer foo
String status
static belongsTo = [alpha:Alpha]
static constraints = {
status(nullable:false, inList:["val1","val2","val3", "val4"])
}
}
I'd like to have in Alpha the sum of all Beta.foo and of all Beta.foo in a certain status. Best would be something like an additional row ( Integer sumVal1 ... ).
I tried named queries:
static namedQueries = {
erledigterProbeAufwend {
createAlias ('Beta', 'b')
eq ('b.status', 'val1')
projections {
groupProperty('b.alpha')
sum('b.foo', 'sumFooVal1')
}
}
}
But this just give me one sum at a time.
I'm looking forward to get some help on that.
Greetings
Bas

This could be calculated formula field, but with a subquery trick:
static mapping = {
betaCount formula: "(SELECT count(*) FROM Beta b WHERE b.alpha_id = id and b.status in('a', 'b'))"
}

Create transient variables in your Alpha class and populate them in an onLoad event.
class Alpha {
String a
String b
etc.
static transients = ["sumVal1",...]
static hasMany = [beta:Beta]
def onLoad = {
sumVal1 = ....
}
}

Related

How to save addTo in order by given date/id?

I need some help on my API, when I'm on web, the order is saving correct, but when its on API, it goes all wrong:
def test = parseJSON.sort { a, b -> a.ID <=> b.ID } //or dateTime, will print the same
//order when I print each of them
[IDWeb:0, conductivity:0, ReportId:2, dissolvedOxygen:0, levelWater:1, ID:1, ph:0, redoxPotential:0, temperature:0]
[IDWeb:0, conductivity:0, ReportId:2, dissolvedOxygen:0, levelWater:0, ID:2, ph:0, redoxPotential:0, temperature:0]
[IDWeb:0, conductivity:0, ReportId:2, dissolvedOxygen:0, levelWater:0, ID:3, ph:0, redoxPotential:0, temperature:0]
[IDWeb:0, conductivity:0, ReportId:2, dissolvedOxygen:0, levelWater:4, ID:4, ph:0, redoxPotential:0, temperature:0]
test.each{
def sample = new SampleWater()
sample.levelWater = it.levelWater
sample.conductivity = it.conductivity
sample.dissolvedOxygen = it.dissolvedOxygen
sample.redoxPotential = it.redoxPotential
sample.ph = it.ph
sample.temperature = it.temperature
water.addToSamples(sample)
}
return water
My problem is that addTo is not saving in order. How can I solve this?
Make sure you have defined the type of samples as a List in your Water domain class so that we can maintain the insertion order:
class Water {
static hasMany = [samples: Sample]
List<Sample> samples = []
}
class Sample {
def levelWater
}
By default implementation of hasMany is of type Set which does not maintain the insertion order but is responsible for uniqueness.
Since, now you samples will be saved in the same order as they are inserted.
You have to specify with order you want to apply to the list of SampleWater in the "water" domain class.
i.e:
class BlogCategory {
static hasMany = [
entries : BlogEntry
]
static mapping = {
entries: sort:'dateCreated', order:'desc'
}
}
In this example BlogEntry will be ordered respect dateCreated.

Sorting grails list based off of string from a linked table

I've got two domains, one stored a link to another, like so (I've cut out all the other fields to eliminate noise): -
class TestScenario {
static constraints = {
testscenariodesc(blank:false, maxSize:100, unique: true)
}
static mapping = {
table "test_scenario"
version false
columns{
id column:"test_scenario_id"
}
}
String testscenariodesc
String toString(){
"${testscenariodesc}"
}
}
This is used in: -
class TestExecQueue {
static constraints = {
testscenarioid()
myPriority(inList:[0,1,2,3,4], blank:false)
}
static mapping = {
table "test_exec_queue"
version false
columns{
id column:"test_exec_queue_id"
testscenarioid column:"test_scenario_id"
myPriority column:"Priority"
}
}
TestScenario testscenarioid
Integer myPriority
}
I've got a list in my testexecqueue like so: -
def list(Integer max) {
params.max = 10000
[testExecQueueInstanceList: TestExecQueue.list(params), testExecQueueInstanceTotal: TestExecQueue.count()]
}
But what I want to do is return the results sorted by the testscenariodesc value (not the numeric value of testscenarioID. Is this possible?
I tried this: -
[testExecQueueInstanceList: TestExecQueue.list(params, sort: "testscenarioid", order: "desc"), testExecQueueInstanceTotal: TestExecQueue.count()]
But when I then go to the page I get the following error:
No signature of method: testautomation.TestExecQueue.list() is applicable for argument types: (java.util.LinkedHashMap, org.codehaus.groovy.grails.web.servlet.mvc.GrailsParameterMap) values: [[sort:testscenarioid, order:desc], [action:list, ...]] Possible solutions: list(), last(), list(java.util.Map), first(), last(java.lang.String), last(java.util.Map)
What am I doing wrong here? Thanks for any suggestions! :)
The list() method accepts sort and order parameters. Take a look at the documentation for details. For example
def results = myDomain.list([max: 10, sort: 'myColumn', order: 'asc'])
Alternatively you can specify a default sort order on your domain. For example:
class MyClass {
String myColumn
static mapping = {
sort 'myColumn'
}
}

Fast way to get to perform a request from multiple hasMany association

What is the fast and best way to perform a request from multiple 'hasMany' association ?
Here's a simple code that I have.
From the instance of A I want to get all instances of B domain (a list of id) where login == "toto"?
class A {
static hasMany = [BList:B]
}
class B {
static hasMany = [CList:C]
}
class C {
static hasMany = [DList:D]
}
class D {
String login
}
Thanks
You can do it with an HQL:
String query = """
from a.bList
where a = :a
and exists (select 1
from C c
, D d
where d.c = c
and c.b in a.bList
and d.login = :login)
"""
def result = A.executeQuery(query, [a: aInstance, login: "login"])
More information about executeQuery in the docs.

Grails: Children of Children

I have a question about GORM and "multiple" hasmany relationships, and I didn't find an answer in my previous searches.
Let's say we have three domains:
class A {
...
static hasMany = [Bs: B]
}
and
class B {
...
static belongsTo = A
static hasMany = [Cs: C]
}
and
class C {
static belongsTo = B
String name
dateCreated date
}
I want to know if it is possible to get a list of objects of the class C, sorted by dateCreated, using an object of the class A (something like C.findAll(...., a: a.id) ) or if I have to use a more complex query ?
Best regards,
Its a little more difficult because you aren't storing a back reference to the parent objects
Something like this - I didn't test it myself
A.executeQuery("select distinct c from A a join a.bs as b join b.cs as c where a = :a", [a: a])
If B has:
static belongsTo = [a:A]
then you can do:
C.withCriteria {
a{
eq('id', <a's id here>)
}
order('dateCreated', 'desc')
}

Getting a count of records for the table with hasMany relationship

I've got color and shade domains in my grails application.
class Color {
static hasMany = [shades: Shade]
}
class Shade {
static belongsTo = [color: Color]
}
Using criteria, how can I get a list of Colors where there are X shades? where X is a number that I can pass in.
I know that this returns entire list of colors:
def list = Color.createCriteria.listDistinct {
shade {
count()
}
}
but I don't know how to get list where shade count is specific. I tried this but it didnt work.
def list = Color.createCriteria.listDistinct {
shade {
count() == 5
}
}
Looking at the docs the sizeEq seems to be the the criteria method which fits your needs:
def list = Color.createCriteria().listDistinct {
sizeEq("shades", 5)
}

Resources