Search code examples
exceptiongrailsimportduplicatesmappings

Grails package change for domain class caused DuplicateMappingException


While working through a tutorial to start learning Grails, I made a mistake and ran:

grails create-domain-class com.FooBar

instead of:

grails create-domain-class com.acme.FooBar

It was immediately obvious I had made an error so I tried the following:

  1. Searched for a function that reverses the create-domain-class command, it seems there isn't one.
  2. Searched for advice on the web and the consensus is that you can delete a domain class file, any associated views and tests, then to be safe run a text search for your class name in your project directory for any references you may have missed. I have done all this.
  3. Then I ran the correct command to create com.acme.FooBar, which worked.

After this the app fails to run and reports the following error:

org.hibernate.DuplicateMappingException: duplicate import: FooBar refers to both com.acme.FooBar and com.FooBar (try using auto-import="false")

After adding the following code to com.acme.FooBar:

...
static mapping = {
    autoImport false
}
...

The app now runs as expected.

However as an experienced Java developer who occasionally does refactor a package I would like to understand how to do that without causing a DuplicateMappingException or resorting to the "autoImport false" solution.

Thanks.


Solution

  • You shouldn't be doing

    static mapping = {
            autoImport false
        }
    

    As, by doing this you said that don't check for domain just by name and look up for package as well. Hence, once you do that you will have to use Fully qualified name of the class in your queries / hqls which may itch sometimes.

    You should be removing the Domain completely i.e.

    1. remove the Domain
    2. remove the view folder creating by default with very same name and so do the controller
    3. Now, do grails clean-all(Make it a thumb rule to use grails clean-all first for any issue unexpectedly occuring).
    4. To be more accurate do remove target directory from your project and then do run grails run-app.

    I had done very same thing many times and got it resolved by above steps.

    Hope it helps.