How can I get all the data of one column in grails? - 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')
}
}

Related

How to set value inside nested forEach() in java8?

I have a case in which I am iterating the List<DiscountClass> and need to compare the list value with another List<TypeCode>, based on satisfying the condition (when Discount.code equals TypeCode.code) I need to set Discount.setCodeDescr(). How to achieve this with nested forEach loop in java 8? (I am not able to set after comparing the values in java 8 forEach).
for (Discount dis : discountList) {
for (TypeCode code : typeCodeList) {
if (dis.getCode().equals(code.getCode())) {
dis.setCodeDesc(code.getCodeDesc());
}
}
}
A possible solution using java 8 lambdas could look like this:
discountList.forEach(dis -> {
typeCodeList
.stream()
.filter(code -> dis.getCode().equals(code.getCode()))
.findAny()
.ifPresent(code -> dis.setCodeDesc(code.getCodeDesc()));
});
For each discount you filter the TypeCodes according to the code and if you find any you set the desc poperty to the one of the found TypeCode.
The other answer showed how to convert a nested loop to a nested functional loop.
But instead of iterating over a list of TypeCode, it's better to use a HashMap to get random access, or an enum like this:
public enum TypeCode {
CODE_1("description of code 1"),
CODE_2("description of code 2");
private String desc;
TypeCode(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
}
public class Discount {
private String typeCode; //assuming you can't have the type as TypeCode
private String desc;
public Discount(String typeCode) {
this.typeCode = typeCode;
}
//getters/setters
}
Then your code will change to:
Discount d1 = new Discount("CODE_1");
Discount d2 = new Discount("CODE_2");
List<Discount> discounts = List.of(d1, d2);
discounts.forEach(discount ->
discount.setDesc(TypeCode.valueOf(discount.getTypeCode()).getDesc()));

Grails: Find class property based on Date

I have a Grails 2.4.3 application that uses Oracle as the database.
There's a class called User:
class User {
String userName = ""
String userPassword = ""
Date userAdded
}
In a controller i am using the following code to find all user names.
def names = User.where { }.projections { property 'userName' }.list()
Now i want to find User Names based on the date in which they were added to database.
For e.g., if a date range is provided as between 12/01/2014 to 12/12/2014, Now i want to get all the User Names added during that period.
Is there a easy way of doing it?
This should do it
Date start = // get the start date
Date end = // get the end date
def userNames = User.withCriteria {
ge('userAdded', start)
le('userAdded', end)
projections {
property("userName")
}
}

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()

Groovy Dynamic Object - How to properly reset properties?

Based on this question I created a Groovy class that will have dynamic properties.
class MyDynamic {
def propertyMissing( String name, value ) {
this.metaClass."$name" = value
value
}
}
So far all good, now I can set some non-existent property with success
MyDynamic dyna = new MyDynamic()
dyna.someProp = new Date()
My problem begins when I have another instance with the same name of property, but with another type
MyDynamic dyna2 = new MyDynamic()
dyna2.someProp = "0" //GroovyCastException: Cannot cast object '0' with class 'java.lang.String' to class 'java.util.Date'
Actually I need this because I'm creating objects with the result of a query without knowing the table and the column. I get the name of the column with the ResultSetMetaData and add the property to the instance of the dynamic object. Later I will use this object to export all the properties and values. In different tables I have the same column name, but with different types.
So my question is: how can I reset this metaClass when I'm done with the instance to not conflict with other instance?
Why not a Expando, a Map or a simple container:
class Dynamic {
def properties = [:]
void setProperty( String name, value ) {
properties[name] = value
}
def getProperty(String property) { properties[property] }
}
d = new Dynamic()
d.name = "yeah"
assert d.name.class == String
d.name = new Date()
assert d.name.class == Date

namedQueries error 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

Resources