Search code examples
grailsgroovygrails-domain-classgrails-controller

Domain class not accessible in my controller


I'm new to Grails and groovy..
I created a domain class

\grails-app\domain\Abc

Now i created a controller in

\grails-app\controllers\myapp\myController

In that, when i created an object it shows error.

def Abc obj = new Abc

The error i got is

unable to resolve class Abc 

I tried to import, but didn't shown there also. Me working in grails 1.3.7 and IntelliJ IDEA 10.0.2
Thank you


Solution

  • Make sure that the location of each class is consistent with the class and package declaration.

    I created a domain class

    \grails-app\domain\Abc

    This class should look like this

    class Abc {
        // implementation omitted
    }
    

    make sure you have no package declaration, because based on the location, this class should be in the default package (which is actually a bad practice). Ideally you should put this class into a package, then move the source file into a subdirectory of \grails-app\domain that corresponds to the package name.

    Now i created a controller in

    \grails-app\controllers\myapp\myController

    This class should look like this

    package myapp
      
    class myController {
        // implementation omitted
    }
    

    Notice that this class should be named with a lower-case 'm' because that's how the file is named. The standard Java/Groovy naming conventions dictate that classes should begin with a capital letter.

    In that, when i created an object it shows error.

    def Abc obj = new Abc
    

    There are a couple of problems with this code:

    • define the type as either def or Abc but not both
    • you're missing some parentheses

    Try this instead:

    Abc obj = new Abc()