Grails Create Multiple Value Map - grails

I have a list of Clients and each client has one or more Venues.
These are two separate Domain classes where Venue has client id
I want to create a multiple value MAP which will have Client name as Key and Venue names as value
example :
def dataMap=["Client1":["Venue1","Venue2","Venue3"],"Client2":["Venue1","Venue2"]]
Domain Class:Client
class Client {
String name;
static hasMany = [venues: Venue];
}
Domain Class:Venue
class Venue {
String name;
String addressLine1;
String addressLine2;
String City
static belongsTo = [client: Client];
}

The same as aiolos wrote, with the standard Groovy method collectEntries():
def dataMap = Client.findAllWhere(/*yourCondition*/).collectEntries { client ->
[(client.name): client.venues.name]
}

What have you tried before and where do you stuck?
Here is one simple approach:
def dataMap = [:]
Client.findAllWhere(/*yourCondition*/).each { client ->
dataMap[client.name] = client.venues.name
}

Related

Grails - findAll joining two tables

I'm new to Grails. I'm having problem with retrieving data from DB. I have domains with classes, something like...
class Lightbox {
String name = ''
String link = ''
static hasMany = [users: LightboxUserAccount]
}
class LightboxUserAccount {
UserAccount userAccount
static belongsTo = [lightbox: Lightbox]
}
class UserAccount {
String username
...
}
I want to list all "Lightboxes" owned by user with ID=4. I was trying
def my_lb = Lightbox.findAll("from Lightbox as lb where lb.users=:userAccount", [userAccount: springSecurityService.getCurrentUser()])
or
def my_lb = Lightbox.findAllByUsers(4)
None of those work for me. What am I doing wrong? Thx
Try this one:
Lightbox.findAll("from Lightbox as lb where :userAccount in (lb.users)", [userAccount: springSecurityService.getCurrentUser()])
So I did it slightly different, using criteria instead. Take a look if interested
static getAllByUserAccount(UserAccount userAccount) {
def criteria = Lightbox.createCriteria()
def my_lb = criteria.list {
users {
eq('userAccount', userAccount)
}
}
return my_lb
}
It seems to be working. Thanks for responses though

Grails GORM query multiple cascading one to many relationship levels

In Grails I have these 4 domain classes:
package com.whatever.ts4
class A_class {
String aName
static hasMany = [b_class: B_class]
}
package com.whatever.ts4
class B_class {
String bName
A_class a_class
static hasMany = [c_class: C_class]
static belongsTo = [A_class]
}
package com.whatever.ts4
class C_class {
String cName
B_class b_class
static hasMany = [d_class: D_class]
static belongsTo = [B_class]
}
package com.whatever.ts4
class D_class {
Long rowNumber
String dataValue
C_class c_class
static belongsTo = [C_class]
}
Simple ER diagram:
A_class 1=>many B_class 1=>many C_class 1=>many D_class
I'm successfully populating them in BootStrap.groovy
Now,given an single A_class id, I need to obtain a set with these columns:
aName, bName, cName, rowNumber, dataValue
Can I do that using namedQueries?
I’ve tried putting this in the A_class domain class:
static namedQueries = {
myNamedQuery { aid ->
createAlias b_class,'b'
createAlias 'b.c_class','c'
createAlias 'c.d_class','d'
eq 'id',aid
}
}
I like the idea of a named query, because this result set will need to be returned for different A_class id’s. I can utilize a Service to prep the data and call it via the Controller which will render it as JSON (I digress). But, perhaps there is a Groovier way?
You don't need named query for this kind of action. You will obtain all information that you need just by taking it from A_class entity. For example:
def a_class_entity = A_class.get(id)
def b_names = a_class_entity.b_class.bName // set of all bNames
//<-- Not sure if flatten() works with spread collection fields, but it should -->
def c_names = a_class_entity.b_class.c_class.flatten().cName // collection of all cNames
def rowNumbers = a_class_entity.b_class.c_class.d_class.flatten().rowNumber // collection of all rowNumbers
def dataValues = a_class_entity.b_class.c_class.d_class.flatten().dataValue // collection of all dataValues

Need help creating Grails executeQuery based on domain and lookup table

I have two classes: sample, and parameter. I also have a sample_sample_parameter lookup table which exists to hold the sample id and the parameter id. This is mapped in my grails app.
I was able to write an sql query that works in squirrel:
select s.* from sample s, sample_sample_parameters sp where s.id = sp.sample_id and sp.sample_parameter_id = 41
where 41 would be replaced with the parameter.id variable passed from the gsp page to the action. I have also tried to make it work with executeQuery but it tells me that sample is not mapped.
How do I turn this query into a gorm recognizable form?
class Sample {
Date collectionDate // date the sample was collected
Date sampleReceivedDate // date the sample arrived on site
Date dateCreated
String sampleComments // details about the sample
String labAccessionID // internal reference
String sampleGender // is it from a male or female?
String sampleAge // the age of the animal the sample was taken from
String sampleBreed // the breed of animal
String sampleNameID // patient name
String filepath
String enteredby
String sg
String mosm
static searchable = true
static hasMany =[sampleParameters:SampleParameter, ficsruns:Ficsrun]//[tags:Tag]// a Sample can have many parameters
/* mappedBy allows two tables share a common table. It creates two join tables, one for each.
* SampleParameter is the table being shared by Sample and SampleType tables */
static mappedBy=[sampleParameters:"samples"]//[tags:"domainClass1s"]/*http://www.van-porten.de/2010/09/multiple-many-to-many-in-grails/*/
static belongsTo = [sampleType:SampleType, labFinding:LabFinding, sampleSource:SampleSource, species:SpeciesList] // creates dependencies
static constraints = {
sampleType(blank:false)
sampleNameID(blank:false)
collectionDate(blank:false)
sampleReceivedDate(blank:false)
sampleComments(nullable:true, maxSize:1000)
labAccessionID(nullable:true)
sampleGender(blank:false, inList:["M","F","NM","SF", "UNK"])
sampleAge(nullable: true)
sampleBreed(nullable:true)
sampleSource(blank:false)
species(blank:false)
labFinding(nullable:true)
filepath(nullable:true)
enteredby(nullable:true)
sg(nullable:true)
mosm(nullable:true)
dateCreated()
}
/* This section is for static mapping to the hematology database*/
static mapping = {
version false
id generator:'sequence', params:[sequence:'SHARED_SEQ']
}
String toString(){
"${sampleNameID}"
}
}
class SampleParameter implements Comparable{
String name
String value
static hasMany = [
samples:Sample, //domainClass1s: DomainClass1,
sampleTypes:SampleType //domainClass2s: DomainClass2
]
static mapping = {
version false
id generator:'sequence', params:[sequence:'SHARED_SEQ']
}
static mappedBy = [samples:"sampleParameters",sampleTypes:"sampleParameters"]//[domainClass1s: "tags", domainClass2s: "tags"]
static belongsTo =[Sample,SampleType] //[DomainClass1, DomainClass2]
static constraints = {
name(blank:false)
//value()
//value(unique:true)
value (unique: 'name')
}
#Override public String toString() {
return name + " " + value
}
#Override
public int compareTo(Object o) {
if (o == null || this == null) {
return 0;
} else {
return value.compareTo(o.value)
}
}
}
As a first suggestion, when you have the paramter's id, do the following.
Parameter p = Parameter.get(params.id) // or wherever your id is stored
List<Sample> samples = Sample.findAllByParameter(p) // this assumes, the parameter property is actually named 'parameter'
Of course there is no error handling in place right now, but you'll get the idea.
Welcome to GORM, welcome to Grails.
The problem is that you're not using a HQL query in your executeQuery method. Instead you're using native sql. From the manual:
The executeQuery method allows the execution of arbitrary HQL queries.
Take a look at the specification to see ways of doing that. Which, by the way, are way easier than native sql.
List<Sample> samples = Sample.findAllBySampleParameter(SampleParameter.get(variable))
Give it a try?

Grails: master domain field by detail domain field [hasMany]

There are domains:
class Order {
static hasMany = [execDepartments: Department]
String orderNo
//boolean signature
...
}
class Department {
String name
...
}
I want to add boolean signature field for Order but by Department, so I need field signature by execDepartments for Order. Is it possible? Please help.
Is this an m:m relationship?
why not create another domain like
class Order {
static hasMany = [execDepartments: DepartmentOrder]
String orderNo
//boolean signature
...
}
class DepartmentOrder{
boolean signature
Order order
Department department
}
class Department {
String name
static hasMany = [execOrders: DepartmentOrder]
}
Then you can write the belongTo
What you need is a list of signatures in the Order domain.
Possibly an OrderSignature domain that maps signatures to orders.

grails - how to save ArrayList in db

I use grails-1.3.2 and hbase plugin.
I have some difficulty in creating one-to-Many association with
hbase (i can work with hibernate), so
i decided to try create one-to-Many association with using ArrayList.
Here are my domain classes and controllers:
class Contacts {
String con
static constraints = {}
}
class ContactsController {
def create = {
def contact = new Contacts()
contact.con = params.con
contact.save(flush:true)
}
}
class User {
String firstname
String lastname
// static hasMany = [contact: Contacts]
static ArrayList<Contacts> contact
static constraints = {}
}
class UserController{
def create = {
def user = new User()
user.properties = params
user.save(flush: true)
}
def addContact = {
def user = User.get(params.userID)
def contact = Contacts.get(params.contactID)
user.contact.add(contact)
user.save(flush:true)
}
}
In addContact action user.contact = null, so it can not work.
In user does nor appear contact field.
Can someone help me understand what i have to do for saving ArrayList in db?
I don't know anything about hbase, but the static contact property of the User class looks very suspicious. The fact that this property is static, implies that every user has the same contact list, which seems unlikely to be the desired behaviour.
In a standard GORM domain model - assuming you want each User to have their own contact list - this would be defined
class User {
String firstname
String lastname
static hasMany = [contact: Contacts]
}
Although it looks like we're also defining a static property here, it's actually just the definition of how the Contact and User classes are related (AKA mapping) that is static. The contact property that is dynamically added to the User class is non-static.
Aside
I recommend renaming the Contacts class to Contact and the contact property to contacts. The GORM mapping would then look like this:
class User {
String firstname
String lastname
static hasMany = [contacts: Contact]
}

Resources