Grails criteria duplicate association path error - grails

I am trying to use aliases along with the normal association names in a criteria which is giving me "duplicate association path error" my classes are as follows
class FlightReservation{
Flight flight
User usr
String title
}
class Flight {
String flightNumber
Category category
}
class Category {
String name
}
Criteria query
FlightReservation.createCriteria().list(){
createAlias("flight", "flt", CriteriaSpecification.LEFT_JOIN)
flight{
location{
eq("name", "abc")
}
}
order("flt.flightNumber", "asc")
}
Now as i think about it, it seems obvious and perhaps a Hibernate limitation
so i want to know if there's an alternate approach to achieve this
I know i can use fetchMode to load the flight association
but eliminating alias from the query would make things difficult for order clause( which is going to be dynamic and nesting closures would make things ugly)
One might say why can't I use "flt" (alias) in both the places? Actually this other criteria which uses the nested closure instead of alias comes from some other part of the code and I am supposed to reuse that code.
Let me know, if the question isn't clear enough, any insights on this error would be really helpful.

Related

Building a search criteria thats tricky?

I am trying to do a search on my database IndividualRecords by first building a search criteria but its syntax is getting a little tricky for some values. Its easy to set a criteria for an exact field like if the firstName field has 'John' in it I would put this predicate in my criteria:
IndividualRecord.withCriteria {
if (predicates.firstName != null) {
eq 'firstName', predicates.firstName
}
}
But if they also add that they want to search for US citizens, I can't simply do,
if (predicates.UScitizenship) {
eq 'citizenship', predicates.citizenship
}
because I want to look for records based on citizenship 'US', 'Us', 'uS', and 'us'(case insensitivity must be taken in to account) so how would I get around this?
and then here is where the real fun starts. Say I want to find only foreign citizens. I do have a low level mongodb api method that tells me if the citizenship is a valid one by returning true if it finds it in the database of country codes that I have so I guess I could build another predicate something like pseudocode:
if (predicates.foreign) {
all such people whose !citizenship.caseIgnoreEquals('US') && matchCountry(it.citizenship)
}
meaning that all such people whose citizenship isn't 'US' and matches the list of country codes I have where matchCountry(String countryCode) is my low level api method for verifying a country code and will return true if its a valid country code.
I am finding it hard to define such complicated predicates' syntax and that is where I need some help. Thanks.
There are two issues at hand here.
First, case sensitivity and insensitivy can be addressed by using ilike instead of equals. So for example:
if (predicates.firstName != null) {
ilike 'firstName', predicates.firstName
}
Secondly, you may want to look at named queries to encapsulate some of your query definitions. This way you can include/exclude them as you see fit. For example:
if (predicates.foreign) {
foreignPersons(predicates) // call to named query which contains logic
}
Using this you should be able to construct very complex queries which are built upon smaller definitions and in turn make them more usable and reusable.

Avoiding subqueries in HQL using Grails

I have two object, a room type and a reservation. Simplified they are:
class Room {
String description
int quantity
}
class Reservation {
String who
Room room
}
I want to query for all rooms along with the number of rooms available for each type. In SQL this does what I want:
select id, quantity, occupied, quantity-coalesce(occupied, 0) as available
from room left join(select room_id, count(room_id) as occupied from reservation)
on id = room_id;
I'm not getting anywhere trying to work out how to do this with HQL.
I'd appreciate any pointers since it seems like I'm missing something fairly fundamental in either HQL or GORM.
The problem here is your trying to represent fields that are not your domain classes like available and occupied. Trying to get HQL\GORM to do this can be a bit a little frustrating, but not impossible. I think you have a couple options here...
1.) Build your domain classes so that there easier to use. Maybe your Room needs to know about it's Reservations via a mapping table or, perhaps write what you want the code to look like and then adjust the design.
For example. Maybe you want your code to look like this...
RoomReservation.queryAllByRoomAndDateBetween(room, arrivalDate, departureDate);
Then you would implement it like this...
class RoomReservation{
...
def queryAllByRoomAndDateBetween(def room, Date arrivalDate, Date departureDate){
return RoomReservation.withCriteria {
eq('room', room)
and {
between('departureDate', arrivalDate, departureDate)
}
}
}
2.) My second thought is... It's okay to use the database for what it's good for. Sometimes using sql in you code is simply the most effective way to do something. Just do it in moderation and keep it centralized and unit tested. I don't suggest you use this approach because you query isn't that complex, but it is an option. I use stored procedures for things like 'dashboard view's' that query millions of objects for summary data.
class Room{
...
def queryReservations(){
def sql = new Sql(dataSoruce);
return sql.call("{call GetReservations(?)}", [this.id]) //<-- stored procedure.
}
}
I'm not sure how you can describe a left join with a subquery in HQL. INn any case you can easily execute raw SQL in grails too, if HQL is not expressive enough:
in your service, inject the dataSource and create a groovy.sql.Sql instance
def dataSource
[...]
def sql= new Sql(dataSource)
sql.eachRow("...."){row->
[...]
}
I know it's very annoying when people try to patronize you into their way of thinking when you ask a question, instead of answering your question or just shut up, but in my opinion, this query is sufficiently complex that I would create a concept for this number in my data structure, perhaps an Availability table associated to the Room, which would keep count not only of the quantity but also of the occupied value.
This is instead of computing it every time you need it.
Just my $.02 just ignore it if it annoys you.

Grails Many-To-Many - Problems of dynamic finder

I hope you can help me guys. Google unfortunately didn't helps me out and my search here at stackoverflow didn't as well :-(
I have two DomainClasses HumanResource and Task with a many-to-many relationship.
Model-Definitions:
Task:
class Tasks {
String name
static belongsTo = [HumanResource]
static hasMany = [humanResources: HumanResource]
//also tried but didn't help -> static fetchMode = [humanResources:"eager"]
}
HumanResource:
class HumanResource {
String name
static hasMany = [tasks: Tasks]
}
I also tried to add an index on the id-field with mapping={} but I also think that's not the solution, it didn't help and I think there is already an index on the id-field.
So, what I did and not works is now to find all human resources for the given tasks! And the tasks comes from Services and they are already fetched in the service model with "static fetchMode = [tasks:"eager"]"!
Controller-Code:
def listHumanResourcesFromTasks = {
def list = HumanResource.findAllByTasks(service.getTasks())
//and I tried also with an own HashMap but didn't work as well
}
I always get an error "org.springframework.dao.InvalidDataAccessResourceUsageException" with an SQL-GrammarException. But I really don't know why. The "service.getTasks()" objects are fully filled (as I wrote with fetchMode = [tasks:"eager"])...
It would be awesome if somebody could give me the winning hint.
Thanks a lot for your time.
Best wishes,
Marco
This sort of query isn't supported - you'd need to use HQL or a criteria query in general. But this particular one is easy since you have a bidirectional relationship. You can get all of the HumanResource instances for a collection of Tasks with this:
def resources = service.getTasks().collect { it.humanResources }.flatten() as Set
It needs to be a Set since the same HumanResource instance may appear multiple times so you need to condense the List into unique instances.

GORM mapping: make an index unique

I'm feeling a little slow today. I'm trying to do something that I think is very simple. I have a Domain class with a property called 'name'. I want 'name' to have an index, and I want the index to require that the 'name' is unique. I've set the unique constraint and tried creating an index. I can't make sense out of the Gorm docs as to how I add the unique attribute to the index. Here's some code:
class Project {
String name
static hasMany = [things:Things]
static mapping = {
name index:'name_idx'
}
static constraints = {
name(unique:true)
}
}
All is well with the above, except when do "show indexes from project" in mysql it shows my name key as not unique. I know the problem is that I am not specifying unique in the mapping, but quite frankly the docs for gorm are making my head hurt. I see all kinds of stuff about columns, but I can't find a single example anywhere on the web that shows what I want to do. I don't need complex mappings or compound keys, I just want to know the syntax to add the unique attribute to the mapping declaration above. Any advice welcome.
I also did a grails export-schema and see the following:
create index name_idx on project (name);
Nothing in that to indicate this index requires unique values
A related followup question would be once I succeed in making that index unique, what type of error should I expect when I go to save a Project instance and the name is not unique? Is there a specific exception thrown? I realize that even if I check that a given 'name' is unique there's still a possibility that by the time I save it there may be a row with that name.
I'm quite sure the syntax to do what I want is simple but I just can't find a simple example to educate myself with. I've been to this page but it doesn't explain HOW the uniqueness is enforced. I'd like to enforce it at the name index level.
The indexColumn allows additional options to be configured. This may be what you're looking for.
static mapping = {
name indexColumn:[name:'name_idx', unique:true]
}
Grails Documentation for indexColumn
If you put only the unique constraint the GORM send DDL to create an unique index on database.
static constraints = {
name nullable: false, unique: true
}

What is the best way to declare sorted association in grails domain classes?

It seems that there are two different ways of declaring sorted associations in Grails :
Method 1 (see here) using default sort order
class Book {
String title
}
class Author {
static hasMany = [books : Book]
static mapping = { books sort: "title"}
}
Method 2 (see here) using SortedSet
class Book implements Comparable {
String title
int compareTo(obj) {
title <=> obj.title
}
}
class Author {
SortedSet books
static hasMany = [books : Book]
}
I am not sure which one to use and what is the difference (if any), pros and cons between using one against the other.
I would appreciate any clarification.
Thank you
I started to dig into how this all works and then found that method 1 is actually busted in current versions of grails (tested in both 1.2.1 and 1.3). When you actually try to retrieve an author and look at it's books, it throws an exception
There is an open defect for it (4089) which has been open for quite a while.
Here's the exception that gets thrown:
ERROR util.JDBCExceptionReporter - Column not found: BOOKS0_.TITLE in statement [select books0_.author_books_id as author1_0_, books0_.book_id as book2_0_ from author_book books0_ where books0_.author_books_id=? order by books0_.title]
If and when they finally fix it, the differences between the two methods are that in method one, sorting is done at the database level. As you can see in the exception above, GORM was trying to do an "order by books0_.title" which would use any database index on the book.title field and return the objects in that order.
The second method would sort the objects in memory at the time that they get inserted into the set (using the compareTo method that was defined).
Until the current bug is fixed, I'd use method 2 because it's the only thing that works. It should be fine for relatively small collections of things. After it's fixed, I'd potentially prefer method 1 as the database should be quicker at doing the sorting with an index on the sort field.

Resources