Conditional Dynamic finder in grails - grails

so i require something like the dynamic finder should change as per the condition, let me explain by code what i mean
the below code find all employee by status and lastdateattended
def employee = Employee.findAllByStatusAndLastDateAttended("INA",dateObject)
now i have two fields in Employee LastDateAttended and LastDateSigned , and now i want that if a record does not have LastDateAttended, then it should find by LastDateSigned , otherwise LastDateAttended, so another condition is like
def employee = Employee.findAllByStatusAndLastDateAttended("INA",dateObject)
and i somehow wants to join and use both the query based on a condition , can it be achieved ?, if possible please help

I think criteria query make sense here, something like following
Employee.createCriteria().list{
and{
eq('status','INA')
or {
eq('lastDateAttended',dateObject)
eq('lastDateSigned',dateObject)
}
}
}

Employee.list().findAll { emp->
emp.status == "INA" && ( emp.lastDateAttended!=null?
emp.lastDateAttended.equals(dateObject):emp.lastDateSigned.equals(dateObject)
)
}

Employee.findAllByStatusOrLastDateAttendedOrStatusAndLastDateAttended("INA",dateObject)

Related

In grails, is there a loop that behaves like findAll but does not collect object?

Currently, im using findAll. But I dont need the list that it returns. return doesnt work in each so I could not use it.
In grails, is there a loop that matched my need or should I use for loop?
If it makes any sense I believe you are trying to use it as a state rather than wanting the results in which case I doubt you would need findAll
so something like
def user = User.findByUsername('username')
Now
if you did
if (user) {
//do something
}
That would tell you there is something found or maybe:
int size = (User.findAllByUsername('username')?.size()) ?: 0
println "found ${size} records"
Ofcourse if you did
User.findAll{}
Thats all then you iterate through it find what you want
instead if you did
//def aa = User.findAll{user=='username'}?.size()
def aa = User.findAll{user=='username'}
if (aa ) {
println "we have something "
}

Is there a 'does not contains' functionality on a collection property of a domain object for createCriteria?

I have a problem similar to this. But I want a does not contain functionality.
Like I have a Post domain. A Post hasMany User.
What I'd like to do, using createCriteria, is something like this:
def c = Post.createCriteria()
def l = c.list (max: maxVar) {
notContains("users", thisUser)
}
I tried using ne But no luck.
def l = c.list (max: maxVar) {
users {
ne('id', thisUser.id)
}
}
To be clear, how can I get list of all the Post whose users field which is a collection does not contain thisUser ?
You can use HQL for this
List<Post> posts = Post.executeQuery("select distinct p from Post p where :myUser not member of p.users", [myUser: user, max: maxVar])
c.list (max: maxVar) { not { 'in'("users", thisUser) }}
Will return a list without thisUser. This works for grails version 2.*. You may need to override .equals for your User class.
There are also many other ways to this such as using .find. Please see this link http://groovy.codehaus.org/JN1015-Collections
I was not able to get a conventional solution to it, but I solved this problem using two separate queries.
First I got all the Posts whose users contain thisUser using
users {
eq('id', thisUser.id)
}
Then I got max number of Post whose id does not match any of the id from above.
Post.findAllByIdNotInList(usersList.id, [max:15])
where usersList is result from first query
P.S. : Please answer if anyone has a better solution. Thanks

how to use ilike with Integer in grails

I use EasyGrid plugin and must find values where integer field like '%001%'
initialCriteria {
ilike('id', "%"+params.id+"%")
}
But ilike doesn't work with Integer. How to do it?
I tried to do:
initialCriteria {
ilike('id'.toString(), "%"+params.id+"%")
}
initialCriteria {
ilike('str(id)', "%"+params.id+"%")
}
but it's not work.
If id is an integer in the database, then ilike doesn't really make much sense and there is probably a better way to do what you are trying to do (like adding a type field or something to the domain object, and filter by type)
However, you should be able to do something like this (untested):
initialCriteria {
sqlRestriction "cast( id AS char( 256 ) ) like '%001%'"
}
Following criteria not working if you search from your textbox when user search any text character by mistake like 12dfdsf as your searchable id. It will give you an exception
initialCriteria {
ilike('id', "%"+params.id+"%")
}
For better use you can use following criteria
initialCriteria {
sqlRestriction "id like '%${params?.id}%'"
}
You could do:
String paddedId = params.id.toString().padLeft(3,'0')
initialCriteria {
ilike('id', "%$paddedId%")
}
The solution offered by tim_yates with the sqlRestriction would work in version 1.5.0 of easygrid.
One of the main differences from 1.4.x is that the gorm datasource no longer uses DetachedCriteria, but Criteria - which maps directly to Hibernate's Criteria API.
So you can try it on the last version.
(Keep in mind that the upgrade might break your existing grids. There's also many other changes)
Another small observation is that 'initialCriteria' is not the right place to do stuff like that. (it's not wrong, but there is a 'globalFilterClosure' property for applying column independent filters)
I mixed the code posted by #tim_yates and mine:
String paddedId = params.id.toString().padLeft(3,'0')
def crit = Book.withCriteria {
sqlRestriction "lpad(cast( id AS char( 256 ) ), 3, '0') like '%${paddedId}%'"
}
I've tried with a h2 in-memory db and it works, but I am not sure about two things:
the real usefulness of that
lpad syntax consistence across all db engines
YMMV

autocomplete, search multiple database tables/fields - Symfony

I have 3 models:
article [name, title]
photo [name, description]
video [name, description, transcription]
Now, I want to create an autocomplete search that will search each of those models and db fields for matching string in the input field.
Is it possible to do a search over these 3 tables?
If so, how would I go about it?
UNION operator is what you're looking for.
I guess your using propel.
Its absolutetly possible to do this, but if these table are not related to anything that could result in some messy code when saving. But if you absolutely need to search in those tables, my approach would be to create an action like:
public function executeAutocomplete(sfWebRequest $request)
{
$q = $request->getParameter('q');//The value to be searched
$limit = $request->getParameter('limit');//Not completly necessary but recommendable
if(count($q) == 0)
{
return sfView::NONE;//With no input, no search
}
$results = array( 'article' => array(), 'photo' => array(), 'video' => array());
$article_search = ArticlePeer::search($q,$limit);
$photo_search = PhotoPeer::search($q,$limit);
$video_search = VideoPeer::search($q,$limit);
$this->process_search($results,$article_search,$photo_search,$video_search);
//Process those three arrays to fit your need
return $this->renderText(json_encode($result));
}
Now, the search function on the Peer classes could look like this:
ArticlePeer>>
public static function search($q,$limit = null)
{
$c = new Criteria();
$c->add(self::NAME,'%'.$q.'%',Criteria::LIKE);
if(!is_null($limit))
{
$c->addLimit($limit);
}
return self::doSelect($c);
}
Finally as for the widget, i have used and adapted sfWidgetJQueryAutocomplete and it work pretty good so you should check it out.
EDIT: The short way to an embbed search field si creating sfForm wit the jQuery widget i mentioned before and leave configuration and js to the widget. You'll have to find a way to handle search resutls.
Well i hope this helped you!

StackOverflowException caused by a linq query

edit #2: Question solved halfways. Look below
As a follow-up question, does anyone know of a non-intrusive way to solve what i'm trying to do below (namely, linking objects to each other without triggering infinite loops)?
I try to create a asp.net-mvc web application, and get a StackOverFlowException. A controller triggers the following command:
public ActionResult ShowCountry(int id)
{
Country country = _gameService.GetCountry(id);
return View(country);
}
The GameService handles it like this (WithCountryId is an extension):
public Country GetCountry(int id)
{
return _gameRepository.GetCountries().WithCountryId(id).SingleOrDefault();
}
The GameRepository handles it like this:
public IQueryable<Country> GetCountries()
{
var countries = from c in _db.Countries
select new Country
{
Id = c.Id,
Name = c.Name,
ShortDescription = c.ShortDescription,
FlagImage = c.FlagImage,
Game = GetGames().Where(g => g.Id == c.GameId).SingleOrDefault(),
SubRegion = GetSubRegions().Where(sr => sr.Id == c.SubRegionId).SingleOrDefault(),
};
return countries;
}
The GetGames() method causes the StackOverflowException:
public IQueryable<Game> GetGames()
{
var games = from g in _db.Games
select new Game
{
Id = g.Id,
Name = g.Name
};
return games;
}
My Business objects are different from the linq2sql classes, that's why I fill them with a select new.
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
edit #1: I have found the culprit, it's the following method, it triggers the GetCountries() method which in return triggers the GetSubRegions() again, ad nauseam:
public IQueryable<SubRegion> GetSubRegions()
{
return from sr in _db.SubRegions
select new SubRegion
{
Id = sr.Id,
Name = sr.Name,
ShortDescription = sr.ShortDescription,
Game = GetGames().Where(g => g.Id == sr.GameId).SingleOrDefault(),
Region = GetRegions().Where(r => r.Id == sr.RegionId).SingleOrDefault(),
Countries = new LazyList<Country>(GetCountries().Where(c => c.SubRegion.Id == sr.Id))
};
}
Might have to think of something else here :) That's what happens when you think in an OO mindset because of too much coffee
Hai! I think your models are recursively calling a method unintentionally, which results in the stack overflow. Like, for instance, your Subregion object is trying to get Country objects, which in turn have to get Subregions.
Anyhow, it always helps to check the stack in a StackOverflow exception. If you see a property being accessed over and over, its most likely because you're doing something like this:
public object MyProperty { set { MyProperty = value; }}
Its easier to spot situations like yours, where method A calls method B which calls method A, because you can see the same methods showing up two or more times in the call stack.
The problem might be this: countries have subregions and subregions have countries. I don't know how you implement the lazy list, but that might keep calling GetCountries and then GetSubRegions and so on. To find that out, I would launch the debugger en set breakpoints on the GetCountries and GetSubRegions method headers.
I tried similar patterns with LinqToSql, but it's hard to make bidirectional navigation work without affecting the performance to much. That's one of the reasons I'm using NHibernate right now.
To answer your edited question, namely: "linking objects to each other without triggering infinite loops":
Assuming you've got some sort of relation where both sides need to know about the other... get hold of all the relevant entities in both sides, then link them together, rather than trying to make the fetch of one side automatically fetch the other. Or just make one side fetch the other, and then fix up the remaining one. So in your case, the options would be:
Option 1:
Fetch all countries (leaving Subregions blank)
Fetch all Subregions (leaving Countries blank)
For each Subregion, look through the list of Countries and add the Subregion to the Country and the Country to the Subregion
Option 2:
Fetch all countries (leaving Subregions blank)
Fetch all Subregions, setting Subregion.Countries via the countries list fetched above
For each subregion, go through all its countries and add it to that country
(Or reverse country and subregion)
They're basically equialent answers, it just changes when you do some of the linking.

Resources