namedQueries error grails - grails

I have a domain class DefectData as follows
class DefectData {
String taskId
String defectId
String defectSummary
String severity
String phaseDetected
String rejected
String loggedBy
String howFound
Date dateFound
String defectType
String defectCause
ProgressData progressData
def DefectData(){}
static constraints = {
id generator:"assigned",name:"defectId"
}
static belongsTo=[taskId:ProgressData]
static namedQueries={
getDefectDataByYearMonth{int month,int year ->
def plannedDate=Date.parse("mm-yy","${month} - ${year}")
}
}
}
I am trying this sort of query, which would enable me to get the count of the defects of which were detected in the "Testing" phase.
def testingDefects(int month,int year){
countTestingDefects=DefectData.getDefectDataByYearMonth(month,year).findAllWhere(phaseDetected:"Testing").count()
println countTestingDefects
}
Though, I am getting this error, that the date is unparseable
testingDefects(03,2012)
Unparsable date "3-12". I just want to list the records on the basis of the month and the year.
What could be the issue?

Just throw away your spaces
def (month,year) = [2,2012]
Date.parse("mm-yy","${month}-${year}")
works for me
Give a try to  Joda-Time if you need more control and ease about date parsing

Related

ElasticSearch Grails plugin

it is my first time to use elasticsearch Grails plugin in my Grails2.5.1application , when i'm trying to search for age=35 using elasticSearchService.search("${age:35}").searchResults or using domainName.search("${age:35}").searchResults the searchresults is empty although there is a record in the DB age is equal to 35. And is there any useful tutorial for using ElasticSearch with Grails.
here is my domain:
class EmploymentSeeker {
String empType
String email
String fullName
String expYears
String socialStatus
Integer nubOfKids =0
String computerKnowledge
String militaryStatus
String haveDrivingLic
String gender
String eduQualification
String hasVehicle
String placeOfStudying
String courses
String currentTitle
String currentEmployerName
Integer age
Date dateCreated
static searchable = {
age boost:2.0
root true
except = ['email', 'fullName', 'placeOfStudying', 'currentTitle', 'currentEmployerName', 'dateCreated']
}
static constraints = {
}
static mapping={
}
}
Looks like you have a rogue '$' in your query string. It probably should be:
elasticSearchService.search("age:35")
${..} is needed only if you are passing in a query and want Groovy to replace the expression before invoking the ElasticSearchService.

How can I get all the data of one column in grails?

I'm new in grails and I'm trying to find the solution but I don't found any question here...
That I want to do is, I have this labels in my domain:
String platform
String appVersion
String name
String id
How can I get only all the data that I have store in appVersion column?
You can try the following code with your domain name
def c = DomainName.createCriteria()
def requiredList = c.list {
projections { //projection does the trick
property('appVersion')
}
}
And if by chance you want to compare any value then:
def c = DomainName.createCriteria()
def requiredList = c.list {
eq('column_name', value_to_compare)
projections {
property('appVersion')
}
}

java.lang.NullPointerException in command object

I want to parse a string to date just before validate a command object, here is my command object code
class ActivitiesCommand {
List schools
List departments
Date from
Date to
static constraints = {
schools nullable:false
departments nullable:false
from blank:false
to blank:false
}
def beforeValidate() {
def from = new Date().parse("yyyy-MM-dd", from)
def to = new Date().parse("yyyy-MM-dd", to)
}
}
but i am getting java.lang.NullPointerException when i try def from = new Date().parse("yyyy-MM-dd", from) or def to = new Date().parse("yyyy-MM-dd", to). What can i do in order to successfully parse the date before validate command object?
I read the command object docs. I got this sample from there. I tried if removing ? beforeValidate does not work, so i understand i need to provide a null safe but i do not know how to do it in my scenario
class Person {
String name
static constraints = { name size: 5..45 }
def beforeValidate() { name = name?.trim() }
}
Thanks for your time.
from and to is set to Date in the Command Object, so request parameter string with from and to names will be converted to a Date and then bound to these field.
If the expected date format matches then binding will be successful.
In your case, from and to in beforeValidate is treated as String instead. If they are String actually then you can make them nullable: false in constraints or do the check as below in beforeValidate:
from = from ? Date.parse("yyyy-MM-dd", from) : new Date() - 1 //for example
Note the appropriate use of Date.parse()

How to set formula in grails domain class?

I am trying to write formula in my domain class which helps me in creating criteria.
class MyClass {
//some fields
Date appointmentTime
String ddmmyy
int year
int month
int day
static transients = [
'ddmmyy',
'year',
'month',
'day'
]
static mapping= {
ddmmyy formula('DATE_FORMAT(appointmentTime)')
year formula('YEAR(appointmentTime)')
month formula('MONTH(appointmentTime)')
day formula('DAYOFMONTH(appointmentTime)')
}
}
Whenever I am trying to use this fields in my criteria it throws error i.e. can not resolve property 'ddmmyy' of 'myClass'.
MyCriteria is:
Date myDate = Calender.instance.time
def results = MyClass.createcriteria().list{
lt('appointmentTime', date+1)
ge('appointmentTime', date)
projections {
groupProperty('ddmmyy')
count('id')
}
}
Any idea why I am getting an exception for this?
You need to make these fields non transient to use in criteria. See reference document
http://gorm.grails.org/6.1.x/hibernate/manual/#derivedProperties

How to exclude some columns with GORM with dynamic finders?

I have the following domain object:
class DbDeployment
{
static constraints = {
startDate(nullable: false)
endDate(nullable: true)
username(nullable: true)
fabric(nullable: false)
description(nullable: true)
status(nullable: true)
details(nullable: true)
}
static mapping = {
columns {
details type: 'text'
}
}
Date startDate = new Date()
Date endDate
String username
String fabric
String description
String status
String details // xml representation of the plan
}
I would like to be able to run a query like this:
DbDeployment.findAllByFabric("f1", params)
but I would like to ensure the column details (which is potentially huge) is not retrieved.
Is there a way to do this?
Option 1: Create an association for the large data field(s)
One suggestion from this answer is to break the large data property out into a separate domain, which will cause it to load lazily. Example:
class DbDeployment {
Date startDate = new Date()
Date endDate
...
DbDeploymentDetails details
}
class DbDeploymentDetails {
String details
static belongsTo = DbDeployment
}
Option 2: Using a new domain + mapping to the original table
An answer on a different question links to a Grails mailing list question which has a great answer from Burt Beckwith, but the SO answer doesn't give an example. For the sake of posterity I'll yoink his example from the mailing list and put it here.
It involves creating another domain class without the large field, and then using its static mapping closure to map to the other domain's table.
class DbDeployment {
Date startDate = new Date()
Date endDate
...
String details
}
class SimpleDbDeployment {
Date startDate = new Date()
Date endDate
...
// do not include String details
static mapping = {
table 'db_deployment'
}
}
Then you can just use the finders on SimpleDbDeployment:
SimpleDbDeployment.findAllByFabric('f1', params)
Burt, it'd be great if you would re-answer with your example from the mailing list; I'll cut it out of mine and upvote yours, since you deserve the credit.

Resources