How to check isEmpty on a List of Lists in Thymeleaf? - thymeleaf

I have the following:
#Data
public class SomeClass {
List<SomeBean> beans = new ArrayList();
}
If I have a List of SomeClass beans, is there an easy way to check whether the beans list is empty?
For example, something like this doesn't work (logically): th:if="${#lists.isEmpty(someClass?.beans)}"
Perhaps a utility that can flatten the lists?
I could instead put this on the server-side, but didn't know whether there was an easy way to do it on the front-end.

For these kinds of things, look at collection selection and collection projection. In your case an expression like this should work:
th:if="${#aggregates.sum(listOfSomeClass.![beans.size()]) == 0}"

Related

Grails createCriteria() used inside Domain classes

Just got to know about the capability of createCriteria() method. Just wanna know that other than applying it on the Controller, is there a way to apply onto the domain classes as well? Probably on its own mapping to a property like:
static mapping = {
additionalInfo: Page.createCriteria().list()
}
Perhaps you may want to simply create a new field based the target field like the below example:
class myInfo {
String additionalInfo
String[] moreInfo // a transient field
getMoreInfo(){
def myresultmap = createCriteria.list{
// insert any other criteria shenanigans
}
return myresultmap
}
static transients = ['moreInfo']
}
In a controller return a view like normal with the Domain instance of class MyInfo
Then use in view like:
<g:each in="${domaininstancefromcontroller}">
${it.moreInfo[0]
</g:each>
see docs.
Hope this helps.
Just wanna know that other than applying it on the Controller, is
there a way to apply onto the domain classes as well?
Criteria queries are not limited to controllers, you can apply them elsewhere using the same syntax that you would in a controller. However, the particular example you show there is probably going to be problematic because you are trying to use GORM inside of the mapping block which is used to configure GORM.

How to print a list of objects in a Velocity template?

This is a pretty basic problem and I'm pretty sure I'm doing something wrong or making some assumption. Here goes.
I'm writing a Jira plugin, which uses the Velocity template system. I have a list of ResultRow objects where ResultRow is a class with a single member variable: String key:
public class ResultRow {
public String key;
}
I have a list of these ResultRows:
List<ResultRow> rows = new ArrayList<ResultRow>();
ResultRow row = new ResultRow();
row.key = "foo";
rows.add(foo);
Map<String, Object> velocityParams = new HashMap<String, Object>();
velocityParams.put("rows", rows);
return descriptor.getHtml("view", velocityParams);
and I am trying to list these rows in a template with the following:
#foreach ($row in $rows)
<tr><td>$row.key</td></tr>
#end
I want the output to be: foo. Maddeningly, the template system simply prints the literal string "$row.key" instead of the contents of key. To verify that "$row" is indeed an object, I used the template:
#foreach ($row in $rows)
<tr><td>$row</td></tr>
#end
and the result was as expected: com.domain.jira.ResultRow#7933f2c6.
I think maybe I'm missing some requirement for the class. Does it need to be defined in some special way to suggest to Velocity that certain members are usable in templates? Does Jira use some special funky version of Velocity that only works with certain objects?
I guess the answer is you cannot do what I was trying to do. You can call member methods but you can't access member variables, which means you'll need to add getters to your class. (Could've sworn I tried that. Ah well.)
Velocity does not expose fields, only methods. There are ways to change that:
You can create your own Uberspect class that allows access to public fields.
You can wrap the instance with a modified version of Velocity's FieldMethodizer that gives access to non-static fields.
You can add and use an instance of a "tool" class to your context, such as a subclass of VelocityTool's ClassTool.

How to override the DomainClass.list() in GORM (Grails)

People, I'm facing a problem with grails GORM, my Application is totally dependent of the DomainClass.list() method, it is in all of my create/edit GSPs, but now I need a particular behavior for listing objects. Being more specific I need to filter these lists (All of them) by one attribute.
The problem is I'm hoping not to change all the appearances of these methods calling, so is there a way to customize the behavior of the default list() method ? I need it to function just the way it does, but adding an ending filter.
Maybe you can use hibernate filter plugin (see here). This will allow you to filter all finder methods (including list()) based on a property:
static hibernateFilters = {
enabledFilter(condition: 'deleted=0', default: true)
}
Have you considered using names queries? You could always do something like this:
class DomainClass {
// ... class members
static namedQueries = {
myList { params->
// put your complicated logic here
}
}
}
Then you can just replace your calls to DomainClass.list() with DomainClass.myList.list().

Multiple search criteria in a repository

I have a question for how to implement multiple criteria for a repository pattern in ASP.net MVC. Imagine a POCO class in EF4
public class people
{ String Name {get;set;}
float Height {get;set;}
float Weight {get;set;}
int age {get;set;}
....
}
If I build up a repository as IPeopleRepository, what kind of methods should I implement for a multiple criteria search (e.g Age > 30, Height >80). Those criteria would be related to the properties in the class and some of the input could be null. Of course I can write a method like
People SearchPeople (int age, float height.....)
but I have to judge if every variable would be null and append onto the search queries..
So do you have any good ideas on how to implement this function in EF?
It sounds like your looking for something like the Specification pattern.
There is a great article involving EF4 / POCO / Repository / Specification pattern here.
Although i like the pattern, i find it a bit overkill in simple scenarios.
I ended up using the "pipes and filters" technique - basically IQueryable<T> extension methods on your objects to make your repository code fluent.
For a search criteria however, i would be tempted to allow the consuming code to supply the predicate, then you don't have to worry about the parameters.
So the definition would be like this:
public People SearchPeople(Expression<Func<People,bool>> predicate)
{
return _context.People.SingleOrDefault(predicate);
}
Then the code simply supplies the predicate.
var person = _repository.SearchPeople(p => p.Age > 30 && p.Height > 80);
Some people don't like this technique, as it gives too much "power" to the consumer, because they might supply a predicate like p.Id > 0 and return all the rows in the database.
To counteract that, provide an optional parameter for maxRows. If it's not supplied, default to 100 rows.
First, you need to think if you really need repository search method.
You might want to do direct queries instead of wrapping them to repository.
However, if you think you need the search method than you will likely use something like this:
private People SearchPeople(int? age, float? height)
{
var baseQuery = db.People;
if (age != null)
baseQuery = baseQuery.Where(arg => arg.Age > age);
if (height != null)
baseQuery = baseQuery.Where(arg => arg.Height > height);
return baseQuery.ToList();
}
Although you didn't want to do this, I can't think of better solution.
Basically I think there are three options:
Use Specification pattern and create as many single specification as you need then you can more complex specification by combining them via And/Or/Not operators. You can look at here for an example http://code.google.com/p/linq-specifications/
Create a search method that accept an input predicate, it's most simple one since it leaves all criteria filtering works to consumers.
Create a search method with different criteria, then build dynamic Linq expression. There is a PredicateBuilder here: http://www.linqpad.net (look for LinqKit project).

Grails select domain objects based on an enum value in an enum list property

I'm having trouble selecting items from a list of domain objects based on a value in an enum list.
My domain object looks like this:
class Truck {
static hasMany = [ makes: Make ]
}
where a Make looks like this:
enum Make {
KENWORTH, MACK, VOLVO
}
I'm not really sure how do something like Truck.findByMake(Make.MACK) to give me all of the Trucks that have this Make in their list of Makes. That call gives me this error:
No property found for name [make] for class [class Truck]
Any ideas? Grails 1.2.2.
This one's tricky and not supported by the dynamic finders. I also don't know how to do this with Criteria queries, but the HQL would be
def mackTrucks = Truck.executeQuery(
'select t from Truck t left join t.makes make where make=:make',
[make: Make.MACK])
You can make ist with criteria query the answer is her in the forum but you have to customize it. Maybe like this:
Truck.createCriteria.list ={makes{eq('name', Make.MACK)}
}
I think each Enum has the attribute name.

Resources