The Scenario is like this:
Every Process has multiple ProcessingSteps
The code that I have written is able to fetch all the processes without correspondence to ProcessingSteps.
I know that I am missing a where clause, I want to ask how do we do that in Grails.
I only want to fetch for each Process the corresponding ProcessingStepUpdate
I have two domain classes ProcessingStep and ProcessingStepUpdate
package a.b.c
public class ProcessingStep {
Process process
}
public class ProcessingStepUpdate{
static belongsTo = [processingStep: ProcessingStep]
ProcessingStep processingStep
}
Here is the script that I was writing
Process.list(max:1).each {
//List<ProcessingStep> test2= ProcessingStep.findAllByProcess(it)
//println it
def test3 = ProcessingStep.createCriteria().list() {
eq("process",it)
}
println it
it.list().each {
//not telling it where to get the list from
ProcessingStep.list().each { pstep ->
def test4 = ProcessingStepUpdate.createCriteria().list() {
eq("processingStep",pstep)
// Projections are aggregating, reporting, and
// filtering functions that can be applied after
// the query has finished.
// A common use for projections is to summarize data
// in a query
/* projections{
groupProperty("processingStep")
}*/
}
println pstep
//List<ProcessingStepUpdate> test = ProcessingStepUpdate.findAllByProcessingStep(it)
//List<ProcessingStepUpdate> test = ProcessingStepUpdate.findWhere()
//println "it"
}
}
}
I have been stuck on this problem in one day.. new to OOPS world!
I'll try to guesss that the task is only to iterate children of children. Then it is like this:
public class Process {
static hasMany = [processingSteps: ProcessingStep]
}
public class ProcessingStep {
static belongsTo = [process: Process]
static hasMany = [updates: ProcessingStepUpdate]
}
public class ProcessingStepUpdate {
static belongsTo = [processingStep: ProcessingStep]
}
Process.list().each{ process ->
process.processingSteps.each { step ->
step.updates.each {
println "Process: $process, Update: $it"
}
}
}
Or even
def updates = Process.list()*.processingSteps.flatten()*.updates.flatten()
println updates.join('\n')
Take a look a Groovy Collections, especially at "star-dot '*.' operator" section.
Related
I'm trying to use the Grails shopping cart plugin found here: http://grails.org/plugin/shopping-cart
I was able to successfully install the plugin in my application, as well as inject the service in my Controller:
class TestController {
def shoppingCartService
def index() {
def s = new DomainObj(name: "A Plain Ole Domain Object")
s.addToShoppingCart()
}
}
This appears to be adding the product to my shopping cart, as I expected. However, the problem I'm encountering now is actually listing the items out from the cart. According to the debugger, after running the above code, the shopping cart does indeed have an item (s) in it, as it returns:
com.metasieve.shoppingcart.ShoppingItem : 1
The item is properly being added to the cart, but now I would like to actually list the name of the item out again, so in this case, I want to display the name A Plain Ole Domain Object. How do I do this?
I'm unsure of the syntax for getting the actual objects back from the cart. The documentation doesn't describe how to do this clearly, as it merely states that the following should work:
def checkedOutItems = shoppingCartService.checkOut()
checkedOutItems.each {
println it['item']
println it['qty']
}
But that outputs
com.metasieve.shoppingcart.ShoppingItem : 1 , which is only a reference to some arbitrary item in the cart. I want to get back the actual name of my item.
Thanks in advance.
EDIT:
My domain class (DomainObj) is defined as follows:
class DomainObj extends com.metasieve.shoppingcart.Shoppable {
String name
static constraints = {
name blank: false
}
}
EDIT #2:
def index() {
def s = new DomainObj(name: "A Plain Ole Domain Object")
s.addToShoppingCart()
def r = new DomainObj(name: "Second Plain Ole Domain Object")
r.addToShoppingCart()
def checkedOutItems = shoppingCartService.checkOut()
println currentItems
println "-----"
checkedOutItems.each {
println it['item']
println it['qty']
}
}
The output of this is:
[com.metasieve.shoppingcart.ShoppingItem : 1, com.metasieve.shoppingcart.ShoppingItem : 2]
com.metasieve.shoppingcart.ShoppingItem : 2
1
com.metasieve.shoppingcart.ShoppingItem : 1
1
According to the documentation it["item"] gives you back the entity of a domain class that extends Shoppable. So in this case when you are printing it out it's calling the toString() method of that domain class. If you want that to return the value of the name property you need to implement your own toString(). Here is such an example
#Override
String toString() {
return name
}
EDIT:
Well as it's not clear from the documentation it['item'] is a pointer to the Shoppable instance which you can then use to query for the actual product in your cart like this:
com.metasieve.shoppingcart.Shoppable.findByShoppingItem(it['item'])
Thus the following will print out the toString() value of your products
checkedOutItems.each {
println com.metasieve.shoppingcart.Shoppable.findByShoppingItem(it['item'])
println it['qty']
}
For testing I created the following domain and controller.
Domain:
package com.test
class MyProduct extends com.metasieve.shoppingcart.Shoppable {
String name
static constraints = {
name(blank: false)
}
#Override
String toString() {
return name
}
}
Controller:
package com.test
class MyProductController {
def shoppingCartService
def index() {
def p1 = new MyProduct(name: 'one')
p1.save(flush: true, failOnError: true)
p1.addToShoppingCart()
def p2 = new MyProduct(name: 'two')
p2.save(flush: true, failOnError: true)
p2.addToShoppingCart()
def checkedOutItems = shoppingCartService.checkOut()
checkedOutItems.each {
println com.metasieve.shoppingcart.Shoppable.findByShoppingItem(it['item'])
println it['qty']
}
}
}
class Client {
String name
static hasMany = [courses:Course]
}
class Course {
String name
static belongsTo = [client:Client]
}
I have this and I want to get all Clients that has a Course with name = "blabla"
I was trying to do : Clients.findWhere(Course.any { course -> course.name = "math" })
You can do this with criteria:
Client.withCriteria {
courses {
eq('name', 'math')
}
}
I believe that the following where query is equivalent to the above criteria:
Client.where { courses.name == 'math' }
or you may find you need another closure:
Client.where {
courses {
name == 'math'
}
}
but I rarely use where queries myself so I'm not 100% sure of that.
There are probably a lot of different syntactical expressions to achieve the same thing. I can say definitively that this works in my project though.
def ls = Client.list {
courses {
eq('name','math')
}
}
I have a Grails application and want to create filters for my domain class using named query.
I have domains Act and Status, StatusName is an Enum:
class Act {
static hasMany = [status : Status]
}
class Status {
Date setDate
StatusName name
static belongsTo = [act : Act]
}
I want to filter Acts which have their most recent Status's name equal to specific name.
For now I have this code in Act:
static namedQueries = {
filterOnStatus { StatusName s ->
status {
order('setDate', 'desc')
eq 'name', s
// I need only first Status, with most recent setDate
// among all Statuses of that Act
}
}
}
But this filter all Acts that have Status with specific name, not only with most recent. I tried to place maxResult 1 in query, but it seems not to work.
Any help would be appreciated.
EDIT: Problem was solved that way:
filteronStatus {
createAlias('status', 's1')
eq 's1.name', s
eq 's1.setDate', new DetachedCriteria(Status).build {
projections {
max('setDate')
eqProperty('act', 's1.act')
}
}
}
see 'namedQueries' from Grails Doc
// get a single recent Act
def recentAct = Act.filterOnStatus(statusName).get()
ADD:
HQL
"select s1.act from Status as s1 \
where s1.name = :statusName \
and s1.setDate = (select max(s0.setDate) from s1.act.status s0)"
NamedQuery
listByStatus { statusName ->
createAlias('status', 's1')
eq 's1.name', statusName
eq 's1.setDate', new DetachedCriteria(Status).build{ projections { max('setDate')} eqProperty('act','s1.act') }
}
I have a grails-plugin called "listadmin" there is a domain model "Liste":
package listadmin
class Liste {
String internal_name
String public_name
Boolean edtiable = true
Boolean visible = true
static hasMany = [eintrage : ListenEintrag]
static constraints = {
internal_name(unique : true , blank : false);
}
String toString() {
"${public_name}"
}
}
I have service called "SECO_ListenService" in the same module (grails-plugin):
package listadmin
class SECO_ListenService {
def getEntriesOfList(String intnalListName) {
def aList = Liste.findByInternal_name(intnalListName)
return aList
}
}
Now I try to call this service from an other module (grails-plugin) called "institutionadmin". The SECO_ListenService should return a list of strings for an select of a domain model in the inistitutionadmin:
package institutionadmin
import listadmin.SECO_ListenService
class Einrichtung {
Long einrichtungs_type
Long type_of_conzept
int anzahl_gruppen
int anzahl_kinder_pro_Gruppe
String offnungszeiten
static hasMany = [rooms : Raum]
static constraints = {
def aList = []
def sECO_ListenService = new SECO_ListenService()
aList=sECO_ListenService.getEntriesOfList("einrichtung_type")
einrichtungs_type(inList: aList)
}
}
If I try to run this application with the both modules. I get the following error:
Caused by MissingMethodException: No signature of method:
listadmin.Liste.methodMissing() is applicable for argument types: ()
values: []
It seemed to be that the service class don't know the "Liste"-domain-model. But I don't know where the error is. I also tried to call other standard methods like "findAll" but without any success.
Has anybody an idea where my mistake could be?
To get a service in a static context you need to access the grailsApplication spring bean. This can be done thought Holders. Example:
class MyService {
List<String> getAvailable() {
return ['A','B','C']
}
}
class MyDomainClass {
String something
static constraints = {
something inList: getSomethingList()
}
static List<String> getSomethingList() {
def myService = Holders.grailsApplication.mainContext.getBean('myService')
return myService.getAvailable()
}
}
I read that a m:m relationship often means there is a third class that isn't yet required. So I have m:m on User and Project, and I created a third domain class, ProjectMembership
The three domains are as follows (minimized for illustration purposes):
User
class User {
String name
static hasMany = [projectMemberships : ProjectMembership]
}
Project Membership
class ProjectMembership {
static constraints = {
}
static belongsTo = [user:User, project:Project]
}
Project:
class Project {
String name
static hasMany = [projectMemberships : ProjectMembership]
static constraints = {
}
}
If I have the ID of the user, how can I get a list of Project objects that they are assigned to?
There are a handful of ways - here are a couple:
def user = User.get(userId)
ProjectMembership.findAllByUser(user).collect { it.project }
or to avoid the query for the User:
ProjectMembership.withCriteria {
user {
eq('id', userId)
}
}.collect { it.project }
Be wary of queries that'll return large result sets - you'll end up with a huge in-memory list of project objects.