String query='test'
def user = User.withCriteria {
ilike('firstName', '%'+query+'%')
or {ilike('lastName', '%'+query+'%')}
or {ilike('email', '%'+query+'%')}
}
above is the sample code i need to find those object if any one of three of these field( firstName lastName email ) contains query string
thnks
Try joining the conditions inside one or
or {
ilike('firstName', '%'+query+'%'),
ilike('lastName', '%'+query+'%'),
ilike('email', '%'+query+'%')
}
You can also turn on SQL debugging to see how your queries get built.
You can do in this way
String query='test'
def crit = User.createCriteria()
def user = User.list{
or{
ilike('firstName', '%'+query+'%')
ilike('lastName', '%'+query+'%')
ilike('email', '%'+query+'%')
}
maxResults(1000)
order("firstName")
}
Related
How can I write the below SQL query in Grails or GORM?
select email, count(*) as c FROM orders GROUP BY email
Use Projections!
def result = Orders.createCriteria().list() {
projections {
groupProperty("email")
count()
}
order("email", "asc")
}
Edit: Or HQL, I guess...
def list = Orders.executeQuery("select email, count(*) from Orders group by email")
list.each { item ->
def email = item[0]
def count = item[1]
println "There are ${count} people with the e-mail address of ${email}"
}
(I just eyeballed that, but I think it's about right, might take some tweaking)
A have class Product:
class Product {
static hasMany = [attributeValues: ProductAttributeValue]
String productId
String manufacturer
BigDecimal price
static constraints = {
productId unique: true, blank: false
manufacturer blank: false
price min: BigDecimal.ZERO
}
}
I want to find all products, which productId contains substring 'filter'.
I wrote next code:
Product.findAll {it.productId.contains(filter)}
But it doesn't work. Why?
this should't work at all!
you have 2 options here:
1) you use propper GORM techniques like criteria query or HQL, the would look like:
Product.findAllByProductIdIlike( "%${filter}%" ) // dyn-finders
Product.withCriteria{ ilike 'productId', "%${filter}%" } // criteria
Product.findAll{ ilike 'productId', "%${filter}%" } // criteria
Product.findAll( "from Product where productId like '%?%'", [ filter ] ) // hql`
2) or use filtering on the whole dataset in grails app's memory (instead of the db) - NOT recommended:
Product.list().findAll{ it.productId.contains(filter) }
You can use regex,
Try this :
def yourProductIsWithFilter = '123filter456'
def matchingPattern = 'filter'
//def patternToMatch = /\b${matchingPattern}/\b
//def patternToMatch = /[A-Z_0-9${matchingPattern}/]
def patternToMatch = ~/.${matchingPattern}/
Product.findAll{it.productId =~ patternToMatch }
Note: I haven't tested the code.
Hope it gives you a heads up.
Regards
I would like to get the field names of a class and maybe store it in a list. Can anyone help? Thanks.
You can try this to get field names of domain class.
YourClass.declaredFields.each {
if (!it.synthetic) {
println it.name
}
}
You can use gormPersistentEntity for any domain object, this works with Grails 2.4.4 at least:
def names = Person.gormPersistentEntity.persistentPropertyNames
//returns ['firstName', 'lastName'...]
you can also get natural name using GrailsNameUtils like so:
def naturalNames = Person.gormPersistentEntity.persistentPropertyNames.collect {
grails.util.GrailsNameUtils.getNaturalName(it)
}
//returns ['First Name', 'Last Name'...]
def capitilizedNames = Person.gormPersistentEntity.persistentProperties.collect{
it.capitilizedName
}
//returns ['FirstName', 'LastName'...]
Just found it out, this one works:
def names = grailsApplication.getDomainClass('com.foo.Person').persistentProperties.collect { it.name }
You can iterate over the fields of a class like this.
YourClass.fields.each { println it.name }
If you need to put them into a list you could use collect() or populate it within the each.
http://groovy.codehaus.org/JN3535-Reflection
do you know how to store the result from
sql.eachRow()
of groovy sql to a list? for example def personList = [] ?
example:
sql.eachRow('select lastname from users where id='active')
What I want is to store the result ie. lastnames to a list ie def personlist = [];
I know I can easily do this by namedQuery and I've already done it. But their is some underlying reason about this. Thanks in advance.
def reqdColName = "lastname"
def query = "select $reqdColName from users where id='active'"
Straight option would be to use the rows() method.
def list= Sql.rows(query) //returns groovyrowresult as list
Another option is you could use the executeQuery instead, to get hold of the resultset of the query and thereby get an array/list on it.
def array = Sql.executeQuery(query).getArray(reqdColName)
//If you need as a list
def personList = Arrays.asList(array)
I know that the question has been asked a long time ago, but still, I feel the answer may be of help for someone out there.
def personlist = []
sql = Sql.newInstance(url, username, password, driver)
query = "select $reqdColName from users where id='active'"
sql.eachRow(query)
{
row-> personlist << row.toString()
}
sql.close()
personlist.each{println it} // you can also return the list
def personList = sql.rows("select lastname from users where id='active'")*.lastname
Below is my code.
Here I am getting an error which is 'No such property: it for class: emp.EmployeeController'.
I think I am doing something wrong here.
Any advice??
def list ={
def id=params.id
def results
String employee="SELECT empName, empDate, empNo from employee where empId='id'"
String referrer="SELECT empName, empDate, empNo from referer where empId='id'"
def employeeInstanceList = new ArrayList<Employee>()
Sql sql = new Sql(dataSource)
def joining=null
joining = sql.rows( "select joining from employee_dates")
if (joining!=null)
results = sql.eachRow(employee)
employeeInstanceList=getCalculatedEmployeeData(results)
/*{
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee
}*/
else
results = sql.rows (currentDaySql)
employeeInstanceList=getCalculatedEmployeeData(results)
/*{
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee }*/
}
[employeeInstanceList: [employeeInstanceList: employeeInstanceTotal: Employee.count()]
}
def getCalculatedImpactData(def results){
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee }*/
return [employeeInstanceList: employeeInstanceList]
}
Thanks,
Meghana
i would second leebutts answer... but just a pointer, the usage of the it keyword is usually confined to closures... so instead of doing this in java:
List l = [];
for (Iterator i = l.iterator(); i.hasNext(); ) {
...do something adressing List l at position i...
}
you could do this in groovy / grails:
list.each { it ->
...do something with each object in the list (it)...
}
but you should really read up on groovy closures at http://groovy.codehaus.org/Closures
There is so much wrong with that code, I don't know where to start...
But to avoid getting more down votes I have tried :)
I tried to copy your code into an IDE and try and work out what you are trying to achieve but couldn't.
This is as close as I could get it:
def list = {
def id = parmas.id
def results
String employee = "SELECT empName, empDate, empNo from employe"
def employeeInstanceList
Sql sql = new Sql(dataSource)
def joining = sql.rows("select joining from employee_dates")
if (joining != null) {
results = sql.eachRow(employee)
employeeInstanceList = getCalculatedEmployeeData(results)
}
else {
results = sql.rows(currentDaySql)
employeeInstanceList = getCalculatedEmployeeData(results)
}
[employeeInstanceList: employeeInstanceList, employeeInstanceTotal: Employee.count()]
}
def getCalculatedImpactData(def results) {
def employeeInstanceList = new ArrayList<Employee>()
results.each { it ->
def employee = new Employee()
employee.empName = it.empName
employee.empNo = it.empNo
employee.empDate = it.EmpDate
employeeInstanceList.add(employee)
}
return employeeInstanceList
}
but it is still referring to a variable currentDaySql which doesn't exist and I'm not sure what you're trying to do with the 'joining' result.
You really need to read up on Groovy basics.
The block of code where the error occurs is probably:
def getCalculatedImpactData(def results){
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee
return [employeeInstanceList: employeeInstanceList]
}
it is not defined anywhere (hint: the compilation error told you this). Like Sebastian said, it is typically used in closures; what you've defined here is a function. Presumably you wanted to use results (or something) instead of it here.
I'm assuming that some of the things in your code (e.g. comment opening/closing) weren't in there and were added between when you saw the error and when you posted the code. Otherwise you'd get other errors.