New to groovy, grails.
I have the following query where I want to match a few paramater exactly to as passed(eq), but for one, which I want to using a 'like'
if (params.ret_code) {
ret_cod = params.ret_code+"%"
}
def srchresults = DmnObj.where {
if (params.doc_num) { doc_num == params.doc_num.trim() } //works as expected
//How do I do this????
if (params.retn_code) { retn_code like ret_cod }
}
Tried this, but in-vain.
how do I set retn_code with a like?
Thank you!
This is how you can do this
// case sensitive like
def result = Domain.where {
fieldName ==~ "value"
}
// case insensitive like
def result = Domain.where {
fieldName =~ "value"
}
Remember to prefix, suffix or both the value with %. For more about where queries https://grails.github.io/grails-doc/latest/guide/GORM.html#whereQueries
You can do like this:
var feel []DB.Feelings
db.Where("column_name LIKE ?", "%"+yourText+"%").Limit(your_limit).Offset(your_offset).Find(&feel)
column_name is your column name
Limit and Offset are not required
You can do like this:
def result = DomainClass.where{
like('fieldName', '%'+myVariable+'%')
}
I suggest you have a look at the Grails documentation (section Domain Class Usage): you will find several interesting ways to filter your domain class objects as for example HQL queries or findAllBy* dynamic methods.
Related
I've a scenario to pass a List of char values to the query in Grails.
When I pass the List this is what happening
def accounts = ['A', 'B']
AND acct.account_status_cd in '${accounts}
the query looks like "AND acct.account_status_cd in '[A,B]'"
but it should be "AND acct.account_status_cd in ('A','B')"
how to achieve this?
Resolved it by Passing as a String...
String s = keys.collect { "'$it'" }.join( ',' )
It gives me S = 'A','B','C'
A solution could be a NamedQuery inside your domain class, something like this:
class Account {
// code omitted
static namedQueries = {
accountsInList { accountList ->
'in'("account_status_cd", accountList)
}
}
Then you can use this namedQuery like:
Account.accountsInList(['A', 'B']).list()
Ofcourse you can also use a withCriteria.
See the docs for more info:
http://grails.org/doc/2.2.x/ref/Domain%20Classes/createCriteria.html
I have a simple Tag class with only two fields, name and value,
class Tag {
String name
String value
}
and I'm trying to render an XML where I want to search for parts of both parameters via findBy...Ilike().
def getXml = {
render Tag.findAllByNameAndValueIlike("%${params.name}%", "%${params.value}%") as XML
}
But this doesn't give my any results. If I use only one parameter, it works as I expect:
def getXml = {
render Tag.findAllByNameIlike("%${params.name}%") as XML
}
My next question is probably going to be about filtering the results, and adding other "similar" tags to the returns list, so is there a way to solve the above with something like:
def getXml = {
list = Tag.findAllByNameIlike("%${params.name}%")
list.add(Some other stuff)
list.sortBy(Some thing, maby name length)
}
For your multiple-field ilike query you can use withCriteria:
def result = Tag.withCriteria {
ilike('name', "%${params.name}%")
ilike('value', "%${params.value}%")
}
This will return a list of Tag domains whose name matches the provided name and value matches the provided value.
The Criteria DSL will probably let you do most of the filtering you need, but you can also consider using some of the Groovy collection examples here.
You have to put the restrictions(InList, NotNull, etc) on each field of a dynamic finder. If you do not, it assumes equals. Here is what you were looking for:
Tag.findAllByNameIlikeAndValueIlike("%${params.name}%", "%${params.value}%")
Both answer are good. I tried both, but I have to say I like the withcCritia the best. It seems very flexibly.
def result = Tag.withCriteria {
if(params.name != null)
ilike('name', "%${params.name}%")
if(params.value != null)
ilike('value', "%${params.value}%")
}
result.add(new Tag('name': "something"))
render result as XML
I have the folowing:
class Store{
String name
}
class Shop{
String name
Store store
}
My criteria builder:
def c = Shop.createCriteria()
def results = c.list {
like("name", "Harrods")
like("store.name", "McDonals")
}
I'm sure this is invalid cause i'v tested it. How can i manage to use criteriaBuilder and do this: like("store.name", "McDonals")?
Looking forward to get any help,
John
Since you're querying an association, try:
def results = c.list {
like('name', 'Harrods')
store {
like('name', 'McDonals')
}
}
This will do an conjoined query between name and store.name.
Check out the documentation Looks like you need to use a % for your like clause.
Imagine I have the following query:
def result = Test.createCriteria().list(params) {
// image here a lot of assocs, criterias, ...
}
In many cases you need the row count of the query above, e.g. list actions of many controllers.
def resultTotal = Test.createCriteria().list(params) {
// Imagine here a lot of assocs, criterias, ...
// Change to the criteria above is only the projection block
projections { rowCount() }
}
How can I avoid this?
You can:
Extract the Criteria creation to a conditional factory/builder method;
Use named queries;
Use named query parameters (and Groovy code!) to alter the query "on the fly", like:
.
static namedQueries = {
byLocation { Location location ->
if (location) {
... // some more criteria logic
}
}
}
If you aren't paginating the results of the query, you can simply do the following after the first query is invoked:
def resultTotal = result?.size()
For the same set of query being used at many places, I create them as a closure and change its delegate to the criteria in question.
For example :
def query = {
projections{
rowCount()
}
eq('type', myType)
}
def criteria = Customer.createCriteria()
query.delegate = criteria
myType = CustomerType.guest
List records = criteria.list(params) {
query()
}
I use totalCount like this:
def list() {
def myInstanceList = MyInstance.createCriteria().list(params){
eq('name', params.name)
}
[myInstanceList: myInstanceList, myInstanceListTotal: myInstanceList.totalCount]
}
Is this possible to convert in createCriteria()?
SELECT * FROM node WHERE (node.type = 'act' AND nid NOT IN (SELECT nid FROM snbr_act_community)) LIMIT 10
I know there's a 'in' operator and here's what I have so far:
def c = VolunteerOpportunity.createCriteria()
def matchingActs = c.list {
node {
eq('type', 'act')
}
maxResults(10)
}
Just want to see if this is possible. Otherwise, I guess this is possible in HQL right?
thanks Sammyrulez for the code. got an idea from that. tested it but it didn't work. i fixed it and here's the final working code:
def ids = [14400 as long, 14401 as long]
def c = VolunteerOpportunity.createCriteria()
def matchingActs = c.list {
node {
eq('type', 'act')
not { 'in'(ids) }
}
maxResults(10)
}
now i know how to use 'not' operator. thanks a lot!
not tried it myself but looking at the Grails doc and hibernate api you create nodes on this builder map with the static methods found in the Restrictions class of the Hibernate Criteria API 1. So something like
def c = VolunteerOpportunity.createCriteria()
def matchingActs = c.list {
node {
not(in('propertyName', ['val1','val2']))
}
maxResults(10)
}
Since you chain the in method (that returns a Criterion) with the not method (that takes a Criterion as argument and returns a negated version)
this is the solution :
def resultat=EnteteImputationBudgetaire.createCriteria().get{
between("dateDebutPeriode", dateDebut, dateFin)
and{ eq 'natureImputationBudgetaire','FONCTIONNEMENT' }
maxResults(1)
}
def resultat2=ParametragePlanBudgetaire.createCriteria().list() {
like('composantBudgetaire','6%')
if(resultat?.details) {
not {
'in'('composantBudgetaire',resultat?.details?.imputationBudgetaire)
}
}
}
According to Grails documentation about creating criteria here, you can use something like this:
not {'in'("age",[18..65])}
In this example, you have a property named "age" and you want to get rows that are NOT between 18 and 65. Of course, the [18..65] part can be substituted with any list of values or range you need.
Just remembering: in this case you don't have to use parenthesis and you can use inList, for example:
not { inList 'age',[18..65] }