GORM « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ GORM ’

Alphanumeric Sorting using Criteria Query (with MySQL database)

Posted by on February 2nd, 2012

I am working on a Grails application with MySQL database. I had a use case in which I had to implement alphanumeric sorting using Criteria Query on Grails. By alphanumeric sorting I mean if there is a class Employee with field empId then on doing :

 
Employee e1 = new Employee(empId:'emp10').save()
Employee e2 = new Employee(empId:'emp2').save()
Employee e3 = new Employee(empId:'emp1').save()
Employee e4 = new Employee(empId:'1emp').save()
Employee e5 = new Employee(empId:'10emp').save()
Employee e6 = new Employee(empId:'2emp').save()

Employee.createCriteria().list([sort:'empId'])
            /* OR */
Employee.createCriteria().list{
    order('empId')
}

should give result like [e4,e6,e5,e3,e2,e1]. But according to sql sorting the result would be [e5,e4,e6,e3,e1,e2]

One thing to note was that criteria query implemented sorting at the database end.
After googling around, I came across a script that had a SQL function which converted the field value to string that can alphanumerically sorted easily at database end.

To migrate the functions in script to database you have to unzip the script and write following command on terminal:

mysql -u username -p database_name < /path/to/unzipped/directory/natsort.install.mysql

Now only thing I had to do was to get a derived field from the Grails property that had to be sorted alphanumerically which was easily possible as the Grails had ability to create transient field using formula (thanks to wonderful Blog by Uday). Thus I had to create a new transient field using SQL function in formula. So I did something like this :

class Employee {
    String empId
    String empIdSortField           //transient field
    static mapping = {
        empIdSortField formula: 'natsort_canon(empId, "natural")'
    }
}

Now if I had to get Employee objects are sorted by empId alphanumerically, what I would do is :

Employee.createCriteria().list {
    order('empIdSortField')
}

Hope this was helpful to you!

Posted in Database, GORM, Grails

My Top 9 Features from Grails 2.0

Posted by on January 18th, 2012

The groovy world is abuzz about the latest release from the Grails Stable, Grails 2.0, which packs a lot more punch than its predecessors, which by themselves were productivity enhancers and wonderful to develop our web applications with. The new version brings with itself a lot of changes compared to the previous releases and deserves to be truly called 2.0 instead of 1.4 or 1.5.

I would like to walk you through some of the coolest features from grails 2.0 that I have discovered in the limited time I have spent with the new version and fell in love with.

  1. The Improved Interactive Mode: I love working on the command line and the new interactive mode is a joy to work with. The auto-completions, combined with the quick response times(as a result of not having to load JVM for each command) is a sure shot productivity booster. That I can run normal commands from the grails shell by just prefixing them with a “!” is an added advantage.
  2. Dynamic Domain Class Reloading: One activity that consumed a lot of time with earlier versions of Grails was waiting for the servlet container to restart, once we made even a line’s change in the domain class or src/groovy file. Now, the reloading is dynamic which means that the changes take effect very quickly, this letting us focus on the development without the flow being interrupted by the restart process.
  3. HTML5 scaffolded screens: One of the complaints I had with earlier versions of grails was the not-so-good looking screens that were generated by scaffolding. For most of the admin screens, the scaffolded screens are sufficient and the new HTML5 compatible scaffolded screens are very easy on the eye and provide an excellent user experience. With the new screens however, I can simply change the logo and they make for sufficiently pleasing CRUD screens.
  4. Business Class Citizenship for Testing: Testing has been a first class citizen of the framework right from day 1, but the new testing framework has made life easy for people like me, for whom testing doesn’t come naturally. With scaffolded tests being generated, newbies will find it easier to learn aspects of testing the application. In addition to that, the capability to unit-test criteria queries adds an element which was missing from earlier versions.
  5. Link Generation/Page Renderer APIs: Earlier, generating html from gsp files from non-request bound threads was a pain, especially with mocking the web request. Now, with the PageRenderer API, generating a view in a job or a service is as simple as injecting a groovyPageRenderer bean and calling groovyPageRenderer.render() method just like from within a controller.
  6. GORM Finders with Groovy Collection find/findAll like syntax: If there was one feature I could keep from all the enhancements in 2.0, it would be this. This is also the feature which, I think would go a long way in making GORM queries easier. There couldn’t be a more expressive syntax!
  7. Public methods in controllers as actions which can take arguments: Earlier, it used to be a pain to type-cast the parameters into their respective types(when one felt that command objects are an overhead while working with at most 2-3 params). The new method like syntax lets us define actions as public methods in controllers, which automatically bind data to the method arguments, based on the params. If I have a command object as argument, it works just the way it worked earlier. We talk about thin controllers a lot. This also means that we’ll be more diligent while creating methods in controllers and even if we really must, they have to be private. This just made the controllers thinner!
  8. The New Improved Test Reports: The new test reports are very easy on the eye and even more easier while finding test failures. Though we don’t recommend having println statements in our test cases, the fact that I can see the system outputs on the same page as my test case is a winner.
  9. DB Console: Viewing the contents of the in-memory DB was a pain in the earlier versions. The new dbconsole, which can be accessed only in development mode is a clear winner.

Grails 2.0 comes with its set of wonderful features which makes development with it, a much better experience.

Posted in Grails

A use case of Bitwise AND

Posted by on April 15th, 2011

Recently, I used bitwise Anding in my grails project. I am sharing the approach that we followed by means of an example.


Suppose we have a domain class Person which can have multiple attributes like Smart, Intelligent, Talkative etc.

What sort of relationship comes to our mind when we see this?
I believe the obvious answer would be Person hasMany Attributes

Next, what if we want to optimize our design so that the searches on the Person becomes better.

Well, this was the question we were facing in our recent project where we finally used the bitwise AND.
We decided to have one field of type Long in our Person class. We named this as attributes . Soon, I ll be explaining why a long for Attribute…

We ensured that the Attributes are never going to be more than 20-30 . So, it became a nice candidate which could utilize the benefit of Bitwise ANDing.

We associated a binary weight to every instance of Attribute domain class.

The rows in the attribute table of our database looked somewhat like this

id | attribute      | weight
1 | Smart          | 1
2 | Talkative      | 2
3 | Intelligent     | 4
4 | Cooperative  | 8
5 | Ignorant       | 16

So, in order to save a Person who is Smart and Cooperative , we would set his attributes field.
weight of Smart + weight of Cooperative.
ie 1+8 = 9.

Suppose our Person table has some entries as follows:

id  | name  | attributes
1   | Tom   |  9
2   | Fred   |  12
3   | John   | 18

If we want to search a person who is Intelligent we need to have a final query like this

Select * from person where attributes&4 = 4
(4 is the weight of Attribute - Intelligent)

Search a person who is Cooperative and Talkative

Select * from person where attributes&2=2 and attributes&8=8
or more optimally,
Select * from person where attributes&10=10
(2 is the weight of Talkative and 8 is the weight of Cooperative)


Some points to be kept in mind before taking this approach:

There is a maximum limit of 64 values for the field on which we plan to do BitwiseANDing.
Bitwise AND is not directly supported by Hibernate, but we can add a custom function and dialect.



Hope this helped.

Thanks & Regards
Mohd Farid

Posted in Database, Grails

GORM Batch Deletes Made Easy with Load Method

Posted by on September 29th, 2010

We are using the grails asynchronous mail plugin in our project and noticed that the sent mails never gets deleted from the database. This was an issue because we were sending out a lot of mails and all of them had PDF attachments of about 500 KB to 1 MB each. A sure recipe for disaster because our DB was growing exponentially. To take care of this, we decided to do a DB cleanup and delete the messages that had the status SENT.

Going through the documents for Deleting Objects, we noticed that grails doesn’t really support batch deletes. The executeUpdate() method, which was provided there as a workaround, was also not a suitable solution because we would’ve had to delete the associations explicitly. This is because executeUpdate() wasn’t doing anything with the associations, which in our case where the attachments.

We found a suitable solution after going through Amit’s blog about loading proxy objects. What we did was something like this.

def sentMails = Mail.findAllByStatus("SENT")
sentMails*.discard() //detach all the objects from session
sentMails.each{
       Mail proxySentMailObject = Mail.load(it.id) //load proxy object
       proxySentMailObject.delete() //using the proxy object to delete from DB
}

This also ensures that we don’t face the ConcurrentModificationException we would have faced if we tried deleting directly using

sentMails.each{
       it.delete()
}

Special Thanks to Amit for the wonderful post which was of great help!

Hope this helps
Vivek
vivek[at]intelligrape.com

http://in.linkedin.com/in/svivekkrishna

Posted in Database, Grails

Ordering using Grails CreateCriteria

Posted by on May 14th, 2010

Recently, in my project I had to implement search functionality. I used grails createCriteria to implement it.Now I needed to apply the sorting on the result returned. My domain was something like this :

class MyEntity {
 
    OrganizationName orgName
    PersonName personName
 
    static constraints = {
      orgName('nullable', true)
      personName('nullable', true)
    }
  }
 
  class OrganizationName {
 
    String organizationName
 
  }
 
  class PersonName {
 
    String familyname
    String firstName
 
  }

The “MyEntity” could either be a person or an organization. In the view, we show just the name, and that could be either the organization-name or person-name. The list needed to be sorted by the name,irrespective of the fact, whether it is a name of a person or an organization. Grails “createCriteria” did the magic for me. I wrote something like this :

  MyEntity.createCriteria ().list {
 
    orgName {
      order('name')
    }
    personName {
      order('familyName')
    }
  }

The ordering seems to ignore nulls. It sorts the MyEntity objects with orgName, groups them togethor and then sorts the MyEntity objects with personName and makes another group for them and then returns a combined, grouped sorted list of both. Hats off to grails.

Imran Mir
imran@intelligrape.com

Posted in Grails, Groovy

How to use table-per-subclass inheritance strategy instead of table-per-hierarchy

Posted by on June 15th, 2008

In this blog I want to share how to use table per sub-class instead of table per hierarchy, which is the default mechanism provided by Grails. I am not sure why Grails chose to use “table-per-hierarchy’. I always find it difficult to understand the table structure produced by “table-per-hierarchy“. Moreover, it makes things difficult for other non-grails application which need to read data from the data database. Another disadvantage is that columns cannot have a "Not Null" constraint applied to them at the db level.

If you are like me and prefer to use a table-per-subclass inheritance strategy, it can be easily achieved using fantastic Grails GORM DSL.

Simply include the following code in all your Grails domain classes.

   static mapping = {
   tablePerHierarchy false
}

This can be simply specified at the root class level and does-not need to be specified for all sub-classes in the hierarchy.

Hope this helps.

-Pradeep Garikipati

Tags: ,
Posted in Grails, Groovy