Mapping duplicate domain class name having different packages using autoImport in Grails

14 / Sep / 2012 by Tarun Pareek 0 comments

Hi,

Recently one of my friend asked me whether there is a mechanism in grails to handle the use-case where we have different packages but having same domain name. Here we are having duplicate domain class names in different package and by default the domain classes are auto-imported in HQL queries which doesn’t required to specify whole class name. Hence due to it class name are no longer unique because of this it cause DuplicateMappingException in our case. For this I refer my friend to set autoImport false in mapping.

Grails provide us a mapping key named ‘autoImport‘. We can disable the auto-import for any one of the domain or both which will fix our problem to some extent. Lets see how it helps :

Suppose we have 2 packages named :
1. com.tarun.poc.project having Domain named “Issue”.
[groovy]
package com.tarun.poc.project
class Issue {
String summary
static constraints = {
}
}
[/groovy]
2. com.tarun.poc.company having Domain named “Issue”.
[groovy]
package com.tarun.poc.company
class Issue {
String description
static constraints = {
}
}
[/groovy]

When you run your app you will recieve the exception some thing like this :
[groovy]
nested exception is org.hibernate.DuplicateMappingException: duplicate import: Issue refers to both com.tarun.poc.project.Issue and com.tarun.poc.company.Issue
[/groovy]

Now we add autoImport to the mapping of domain ‘Issue’ one or both and set it to false as specified below :
[groovy]
package com.tarun.poc.project
class Issue {
String summary
static constraints = {
}
static mapping = {
autoImport false
table ‘project_issue’
}
}
[/groovy]

It will fix your problem regarding ‘DuplicateMappingException’. If you see above we have also specified table mapping because if we didn’t specify table mapping it will create a single table in database with name ‘issue’ and having properties of both the domains into that table.

Hence to create different tables for Domain Class or customizes the name of the database table associated with the domain class we used table mapping.

Hope it helps 🙂

Thanks,
Tarun Pareek
tarun@intelligrape.com

More Blogs by Me

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *