Call namedQuery inside a criteria in controller - grails

Is possible to call namedQuery on grails inside a controller? I know that I can call a namedQuery inside another namedQuery, but i dont want to do that. Any ideas? Thanks
User.groovy
static namedQueries = {
filterUsers{
eq("age", 21)
}
}
MyController.groovy
def r = User.createCriteria().list {
eq("id", 1)
filterUsers() //not possible
}
or..
MyController.groovy
//not possible too
//Cannot invoke method createCriteria() on null object
def r = User.filterUsers().createCriteria().list {
eq("id", 1)
}

Here's an example:
Domain:
class User {
int age
String userName
static namedQueries = {
filterUsers {
eq("age", 21)
}
}
static constraints = {
}
}
Controller:
class TestController {
def index = {
def users = User.filterUsers {
and {
like 'userName', 'Derek%'
}
}
render users as JSON
}
}
Also, you can find more about this here: Reference Documentation

Related

Domain Multiple inheritance and manyToMany relation removeFrom not working

I prepared some complex model structure due to content management businnes.
My main content model likes as following code.
class CmsContent implements Comparable<CmsContent>, Taggable, Serializable {
Set<CmsContent> contents
static hasMany = [contents:CmsContent]
}
Other Content Model extends from above
class Menu extends CmsContent {
}
class Image extends CmsContent {
}
class Video extends CmsContent {
}
On Controller side when ever add Image to Menu it is perfectly working
def addContent(){
Menu menuInstance = Menu.get(params.id)
if (menuInstance == null) {
notFound()
return
}
CmsContent content = CmsContent.get(params.contentId)
if (content == null) {
notFound()
return
}
menuInstance.addToContents(content)
menuInstance.save(flush: true)
request.withFormat {
'*'{
def result =[:] ;
result.status ='success';
render result as JSON
}
}
}
def removeContent(){
Menu menuInstance = Menu.get(params.id)
if (menuInstance == null) {
notFound()
return
}
long id = Long.valueOf(params.contentId)
CmsContent content = cmsContent.contents.find { it.id == id }
if (content == null) {
notFound()
return
}
menuInstance.removeFromContents(content)
menuInstance.save(flush: true)
request.withFormat {
'*'{
def result =[:] ;
result.status ='success';
render result as JSON
}
}
}
But when I tried to remove facing following exception.
Cannot get property 'name' on null object. Stacktrace follows:
Message: Cannot get property 'name' on null object
I tracked down in grails code in DomainClassGrailsPlugin.
I realize that addTo Method and line 368 checking prop.otherSide attribute
if (prop.bidirectional && prop.otherSide) {
}
unfortunately removeTo method not check prop.otherSide attribute, therefore name field throwing the exception.
if (prop.bidirectional) {
if (prop.manyToMany) {
String name = prop.otherSide.name
arg[name]?.remove(delegate)
} else {
arg[prop.otherSide.name] = null
}
}
What do you think ? Do you agree with me ?

Grails search two child objects

I have three domain objects
class OrgProfile {
String name
static mapping = {
discriminator column:'ORG_TYPE'
}
}
class Org extends OrgProfile {
static mapping = {
discriminator 'ORG'
}
}
class Jurisdiction extends OrgProfile {
String email
static mapping{
discriminator 'JURISDICTION'
}
}
I need to search by name and email to get all list of Org and Jurisdiction
so something like
def criteria = OrgProfile.createCriteria()
criteria.list{
or {
ilike("name", "%${token}%")
ilike("email", "%${token}%")
}
}
where token is a string. How can this be achieved?
Tried the code:
def criteria = OrgProfile.createCriteria()
def results = criteria.list{
or {
ilike("name", "%${token}%")
ilike("email", "%${token}%")
}
}
Results as expected.

Restrict the rows retrieved from database for the relationship between the domain classes

I have two domain classes:
class Entity {
static hasMany = [
titles: Title
]
}
class Title {
Boolean isActive
static belongsTo = [entity:Entity]
static mapping = {
isActive type: 'yes_no'
}
}
Now when I am calling Entity.get(0) I would like to take from the database the Entity with id=0, but only with active Titles (where isActive = true). Is it possible in grails? I've tried to add where clause in static mapping of Title domain class:
static mapping = {
isActive type: 'yes_no'
where 'isActive = Y'
}
or
static mapping = {
isActive type: 'yes_no'
where 'isActive = true'
}
but it doesn't work. I am using Grails in version 2.2.1
Could You help me? Thank You in advance.
In this case you can use criteria to do that:
Entity.createCriteria().get {
eq('id', 0)
projections {
titles {
eq('isActive', true)
}
}
}
I don't think it's possible to set a default where to be applied in all your database calls to that Domain Class.
You can also wrap your logic in a service:
class EntityService {
def get(Long id) {
return Entity.createCriteria().get {
eq('id', id)
projections {
titles {
eq('isActive', true)
}
}
}
}
}

How can I create a map with all i18n-messages in Grails

I need this to render a part of it in a controller like:
class MessageController {
def index = {
def messageMap = listAlli18nMessages() // the question
render (contentType: "text/xml") {
messageMap {key, message ->
..
}
}
}
}
Finally I found an answer - override the default Grails messageSource:
class ExtendedPluginAwareResourceBundleMessageSource extends PluginAwareResourceBundleMessageSource {
Map<String, String> listMessageCodes(Locale locale) {
Properties properties = getMergedProperties(locale).properties
Properties pluginProperties = getMergedPluginProperties(locale).properties
return properties.plus(pluginProperties)
}
}
In grails-app/conf/spring/resources.groovy:
beans = {
messageSource(ExtendedPluginAwareResourceBundleMessageSource) {
basenames = "WEB-INF/grails-app/i18n/messages"
}
}
Corresponding controller code:
class MessageController {
def messageSource
def index = {
def messageMap = messageSource.listMessageCodes(request.locale)
render (contentType: "text/xml") {
messageMap {key, message ->
..
}
}
}
}
The approach you are taking doesn't look to be possible based on the API docs for PluginAwareResourceBundleMessageSource. This will get you close to a solution
class MessageController {
def messageSource
def index = {
Locale locale = new Locale('en');
List codes = ['default.paginate.prev','default.paginate.next','default.boolean.true','default.boolean.false']
def messageMap = messagesForCodes(codes,locale)
render (contentType: "text/xml") {
messageMap {key, message ->
..
}
}
}
private def messagesForCodes(codes, locale){
Map messages = [:]
codes.each{code->
messages[code] = messageSource.getMessage(code,null,locale)
}
messages
}
}

idiom for save and update methods in grails

Are there in any idioms in grails which help us with saving domain objects ?
For example
i may want to do something like
if(candidate.hasErrors || !candidate.save)
{
candidate.errors.each {
log it
}
However i do not want to spread the logic across all the places i do domainObject.save.
I also do not want seperate class like say repo to which I pass this domainObject and put in this logic
Thanks
Sudarshan
Here's a service method that I've used to validate and save, but log resolved validation messages on failure. It's helpful to use this instead of just println error or log.warn error since the toString() for error objects is very verbose and you just want to see what would be displayed on the GSP:
class MyService {
def messageSource
def saveOrUpdate(bean, flush = false) {
return validate(bean) ? bean.save(flush: flush) : null
}
boolean validate(bean) {
bean.validate()
if (bean.hasErrors()) {
if (log.isEnabledFor(Level.WARN)) {
def message = new StringBuilder(
"problem ${bean.id ? 'updating' : 'creating'} ${bean.getClass().simpleName}: $bean")
def locale = Locale.getDefault()
for (fieldErrors in bean.errors) {
for (error in fieldErrors.allErrors) {
message.append("\n\t")
message.append(messageSource.getMessage(error, locale))
}
}
log.warn message
}
bean.discard()
return false
}
return true
}
And here's an example in a controller:
class MyController {
def myService
def actionName = {
def thing = new Thing(params)
if (myService.saveOrUpdate(thing)) {
redirect action: 'show', id: thing.id
}
else {
render view: 'create', model: [thing: thing]
}
}
}
Edit: It's also possible to add these methods to the MetaClass, e.g. in BootStrap.groovy:
class BootStrap {
def grailsApplication
def messageSource
def init = { servletContext ->
for (dc in grailsApplication.domainClasses) {
dc.metaClass.saveOrUpdate = { boolean flush = false ->
validateWithWarnings() ? delegate.save(flush: flush) : null
}
dc.metaClass.validateWithWarnings = { ->
delegate.validate()
if (delegate.hasErrors()) {
def message = new StringBuilder(
"problem ${delegate.id ? 'updating' : 'creating'} ${delegate.getClass().simpleName}: $delegate")
def locale = Locale.getDefault()
for (fieldErrors in delegate.errors) {
for (error in fieldErrors.allErrors) {
message.append("\n\t")
message.append(messageSource.getMessage(error, locale))
}
}
log.warn message
delegate.discard()
return false
}
return true
}
}
}
}
This depends on a 'log' variable being in scope, which will be true in any Grails artifact. This changes the controller usage slightly:
class MyController {
def actionName = {
def thing = new Thing(params)
if (thing.saveOrUpdate()) {
redirect action: 'show', id: thing.id
}
else {
render view: 'create', model: [thing: thing]
}
}
}
As a metaclass method it may make more sense to rename it, e.g. saveWithWarnings().

Resources