Friday, August 07, 2009

Using ID tables with Grails

Background and Use Case: We had to migrate one of our web applications to Grails. The old one used JPA and table-based scheme of generating primary key IDs. I scoured the internet with the help of google and found no one with the same problem. I of course had to do it on my own and after going thru the Grails docs, JPA docs and Hibernate docs, I arrived at the solution:
    static mapping = {
        id generator:'org.hibernate.id.enhanced.TableGenerator',
            params:[table_name:'id_table',value_column_name:'gen_id',segment_column_name:'gen_key',segment_value:'fooID']
    }
If you stick the above code in a domain class named Foo, you will end up with a table named id_table and it will have two columns, gen_key and gen_id. If you try saving an instance of Foo, you will end up with:
gen_keygen_id
fooID 1

If you do something similar to the domain Bar, you will end up with:
gen_keygen_id
fooID 1
barID 1

Did it work for you? You are welcome to post your comments/questions or better yet, link to this post, blog about it and tell all your friends who might find this post useful.

No comments:

Post a Comment