Grails Interview Questions ( now with some Answers! )

In the vein of some Java Interview questions, I’ve started thinking of some Grails specific questions I could ask or be asked in job interviews. Here are some of my questions with some answers. Please feel free to submit your own questions or challenge my answers.

Configuration

I have a parameter in my Config.groovy file named layer1.prop1. How can I access this in a controller? How can I access this in a service?
In a controller, I can inject grailsApplication via def grailsApplication and access this variable via grailsApplication.config.layer1.prop.

Anywhere else, I can use the ConfigurationHolder and access it via ConfigurationHolder.config.layer1.prop1

How do I edit the web.xml file of my grails application?
First, I need to generate the template files via grails install-templates. The web.xml template will be under src/templates/war directory.

Alternatively, I could also create a plugin and use the doWithWebDescriptor method to add or remove nodes from my web.xml file.

Explain the concept of externalized configuration. What is this good for?
Externalized configurations let me define other config and .properties files that don’t live within the grails-app/conf directory.

To enable this, I need to define locations for the application to look for configuration files via the grails.config.locations in Config.groovy in relation to the classpath or filesystem.

The most popular uses of externalized configurations is to enable configuration changes without having to re-build a war file. By planning ahead, configurations can even be reloaded without restarting the application container via this mechanism.

Please explain the difference between the Config.groovy and BuildConfig.groovy files.
The Config.groovy file contains configuration properties and information needed when running your application. It contains properties used by your services, controllers, etc.

The BuildConfig.groovy file contains information relevant to building and deploying your application, such as repositories, jar file dependencies and war file name.

Please explain what Bootstrap.groovy does.
Bootstrap.groovy allows you to define code that is ran every time your grails application starts up.

Tools / Shell

What is the difference between the Grails console, shell and interactive modes?
Grails interactive is interactive mode of the grails command line interface. It lets you run Gant scripts in the script runner one after another.

Grails console is a Swing-based command console similar to the Groovy console. It let’s you execute code against a full environment that has access to all your domain classes and quickly test out code that would go into controllers and services.

Grails shell is the headless version of Grails console. This is useful when you want to access and test out code in a remote SSH-based server. One of the advantages of the Grails shell is that it does not reload when domain classes change like the console does, so it is useful also for long-running scripts, although the new run-script command in Grails 1.3.6 might be better suited for those.

How do I get a hold of my Spring beans in the Grails console?
Grails console injects a ctx variable, which represents the Spring context. You can then just use ctx.getBean( ‘myServiceName’ ) to get a hold of your beans.

What are some things I need to be careful about when working with the Grails console?
The bootstrap files don’t get loaded. So if your database is in dbCreate = ‘create[-drop]’ mode, you might not get the same data that you would expect.The console also reloads on code change the same way that grails run-app does. So the code that you have typed in might get lost.

What happens when you call grails bug-report?
Grails generates a dehydrated timestamped minimal zip file that can be attached to JIRA reports. One way to hydrate these into full projects is to call grails upgrade on them.

Which environments are available by default in Grails?
Production (prod), Development ( dev ) and Test

How do I call my custom environment in Grails?
Add the grails.env system property. I.e. grails -Dgrails.env=custom run-app

How do I change the server port of my Grails application?
grails -Dserver.port=666 run-app or via the grails.server.port configuration value

What is the difference between run-app and run-war?
Run-war will compile and builds a war file that it runs from the embedded container ( Tomcat unless you’ve changed it ), run-app runs the application from compiled sources in the file system.

This means that any change to controllers, views, etc will be reflected immediately by run-app, but not by run-war. It also means that scripts that get ran at application packaging time ( such as the ui-performance plugin’s zip and minify process ) won’t happen at run-app time.

How do I create a custom script in Grails?
Call grails create-script myPackage.myScript . This will create a new Gant script file under the scripts directory that you can then run via grails my-script.

What is the _Events.groovy file? What can it be used for?
This file allows us to define event hooks that get called whenever grails scripts fire events. For example, if I wanted to have a utility method that gets fired whenever compilation is finished, I can add it to the CompileEnd metho in _Events.groovy.

My Grails application is in a compile loop and I suspect one of my class names doesn’t match the file name. How do I debug this?
I would pass in the verboseCompile flag and see what kind of monsters lurk in my code. grails compile -verboseCompile

GORM / Databases

Please explain the different options available to dbCreate.

  1. Not having a dbCreate / null – don’t mess with the database
  2. create-drop- nuke the database and create a new one 
  3. create – if the database is there, don’t change it. Otherwise make a new one. 
  4. update – change the database but keep the data if it is there, create a new one if can’t find anything.

What are dynamic finders?
Dynamic finders are methods that are created automatically based on domain class properties by Grails and GORM. They provide a simple way to query domain classes using the power of groovy metaprogramming.

If my domain class Movie has a date called ReleaseDate, I can call Movie.findByReleaseDateGreaterThan( today ) and GORM will automatically resolve this and generate the correct query in the background.

How many parameters can you have at most in a dynamic finder?
3

Closet has many shoes. I want to keep the order of shoes I insert into the closet domain object. How do I do this?
define my shoes in the domain object as List shoes

Please explain what joinTable does within GORM.
The joinTable domain class mapping allows us to customize the table that gets generated for associations. It lets me change the name, primary key and inverse column used in the databse to map a list of primitives, enum, one-to-many or many-to-many relationship.

Please explain what lock() is in GORM and why you would use it.
Sometimes when many people are working on the same set of data, Hibernate will throw a StaleObjectStateException and die.

The lock() method makes sure that nobody else can change your domain class by issuing a pessimistic lock on the database row until you commit your transaction.

What is the difference between calling a read() and a get() in GORM?
read() gets the object in read-only mode. get() retrieves the object and allows it to be modified. One consequence of this is that get() might automatically save changes to the database via hibernate dirty checking while read() will not.

What does the removeFrom() function do in a domain object?
Whenever you have a one-many relationship between a and b, calling a.removeFrom(b) destroys the back reference between a and b. This is the reverse of the addTo() method.

What are named queries? Where do you define them?
Name queries
are aliases written using the criteria builder DSL that allow us to re-use commonly used queries. You put them in the domain classes’ namedQueries static property.

What is the difference between a dynamic finder, a HQL query and a criteria?
All three are used to query domain objects.

Dynamic finders are methods of the form findAllByName( “pancho” ) added to domain classes.

Criterias are a DSL based on Hibernate Criterias and Groovy builders, they look like this: c { like(“name”, “pancho” ) }.

HQL is a query language that looks like SQL but is fully object-oriented. It looks like this: “select distinct s.name from Student.s”

How can you run sql directly in Grails?
Inject the dataSource and pass this as a connection to GSQL ( groovy.sql.Sql ).

new Sql( dataSource ).execute mySqlStatement 

Gorm provides two auto-timestamping variables, what are they?
lastUpdated and dateCreated

Explain Gorm events. Provide two examples.
Gorm events are methods that you can insert into your domain objects and are executed before and after the domain object is saved into the database. Two examples are beforeInsert and afterDelete

I have a property in my domain class that I don’t want to be persisted, how do I make sure it doesn’t generate a field in my database?

You can mark it as such using the static transient = [ ‘cantSaveThis’ ] mechanism.

I have a hibernate HBM file I want to include in my Grails application. Where do I edit this?
You need to create a directory under grails-app/conf/hibernate. Copy your mapping files and create the appropriate hibernate.cfg.xml file there.

How do I inspect the built-in HSQLDB database included with Grails?
You can use the DatabaseManager or DatabaseManagerSwing included with the hsqldb database. Just call the following either in grails console or within your app:

 org.hsqldb.util.DatabaseManagerSwing.main( ['--url', 'jdbc:hsqldb:mem:devDB'] as String[] )

How do I use more than one database in Grails?

You can use the datasources plugin until this functionality is added to grails core.

I have a database and would like to generate Grails domain classes from it, what are my options?

I would first try the reverse-engineer plugin. If that fails, I would try GRAG or assign it to an intern to do manually.

Validation

What are constraints in Grails? Give me three examples.

Constraints let you define the rules for validating a domain object. They are defined under the static constraints closure in a domain object. Three examples might be nullable, blank and email.

Give me two examples of constraints that affect the display within scaffolding views.

  1. widget: ‘textarea’ will make the field display in a text area instead of a one line input field.
  2. display: ‘none’ will hide the constraint from being shown.

Give me two examples of constraints that affect database generation.

  1. nullable: true will cause the database schema to mark the column as nullable.
  2. unique: true will cause the column index to be marked as unique
  3. maxSize: number will set the length of the field to the number.

I want my domain object to throw an exception in Grails if it fails validation, how do I do this?

You should enable the failOnError feature on save.

User.save( flush: true, failOnError: true )

What are Grails command objects? How can they be used in validation?

Command objects are intermediate domain objects that are not saved in the database. You should use them whenever you are just interested in updating a subset of properties from a domain object, or when there is a form that does not map one-to-one with a domain object.

Command objects support both validation and data binding, so you can use these to validate the data entered into forms easily.

What is the difference between validate() and save()?

Save indicates to hibernate that the object should be persisted, validate simply runs all the validation commands and check it. Save runs validate.

I have a class that lives in src/groovy that I want to add validation to. How do I accomplish this?

You can either:

  1. Add the @Validateable annotation to the class and add the package name to the list of packages to validate in Config.groovy
  2. Add the class name to the grails.validateable.classes list in Config.groovy

Controllers

  • Please explain the difference between a controller and a service in Grails.
  • What is the flash object? What other alternatives to the flash object can I use in my Grails application?
  • I have a form with six friend names, all under text inputs named ‘friendName’. What do I need to do to get them as a list in my controller?
  • I want my controller action to return a XML file for some requests and a HTML file for others. How do I accomplish this in Grails?
  • I have a domain object in Grails I want to convert into XML. What do I need to do to ensure that all the children of this domain object are also rendered fully in my XML?
  • What kind of http redirect does the Grails redirect() method issue? How can I change this?
  • What is a Grails Filter?
  • Please explain what params.list does.

View Layer

  • What is the difference between a layout, a view and a template?
  • What are named URL Mapping? How do they differ from normal URL mappings?
  • I want to use a different layout in Grails. How do I do that?
  • What does the pageProperty tag do? How do you use it?
  • Please explain the difference between the <g:form> and <g:formRemote>tags.
  • I have built my own tag library and want all the tags to be of the form <mylib: * > How do I do this?
  • I have a <g:form> but want to make an ajax call when I click on a button. How do I do this?
  • Please explain what the update attribute of the remoteLink tag does in Grails.
  • What does <tmpl:> do in Grails?
  • What are two ways I can specify the JavaScript library used for my Ajax calls?
  • Please explain the <g:include> tag.

Scaffolding

  • Can you explain the difference between dynamic and static scaffolding in Grails?
  • How would you go about changing the default scaffolding templates provided by Grails?
  • What is the RenderEditor.template file? What does it do?
  • What is the difference between generate-views and generate-all?
  • What do I need to run to re-generate all the scaffolding for all my domain classes?

Services

  • I have two services. Service A has static transactional = true defined, Service B does not. How are these two services different?
  • What are service scopes? Can you provide me with three different types of scopes?
  • How do I inject a service to my domain class? From a servlet?
  • I want to use the createLink method available in the Grails standard tag library in my service. How would I do this?

Testing

  • How do I add a configuration value to my unit tests?
  • Please explain the purpose of mockDomain() method in unit tests. Do I have any other alternatives?
  • Grails supports 4 test types. Please list and describe them.
  • Let’s say I want to simulate an XML file being sent to my controller in a test. How would I do this?
  • What does the applyTemplate method do? What does it intend to test?
  • What are page objects? Which grails plugins offer page object support?
  • I want my testing output to be shown on the console, how do I do this?
  • Let’s say I want to execute one single method in my test. How do I do that?

Plugins

  • Please explain the difference between a grails application and a grails plugin.
  • What are in-place plugins? Where do you define them?
  • How do I get a list of all plugins in grails?
  • I want to use a plugin to maintain a record of my database structure. Which plugins should I consider and which would you choose?
  • I want a plugin to help me minify / version / track my css and javascript files. What are my options?
  • I want a plugin to help me set up runnable browser tests. What are my options?
  • I have built the most awesome plugin in the world. How do I submit it to the Grails repository?
  • How do I submit a plugin that is hosted in Github without making a copy in the grails plugin SVN?
  • How would you test the code quality and coverage of your Grails application?
  • What RIA technologies are you familiar with available to Grails?

How did you do?

25 thoughts on “Grails Interview Questions ( now with some Answers! )

  1. Pingback: Grails Interview Questions

  2. Wolfgang Schell

    Great list of questions! I could answer many right away, some I would be able to answer in a general way without knowing the details, some others I would have to look up.

    In “View Layer” there are missing elements (at least I can’t see them):
    “Please explain the difference between the ==MISSING== and tags.”
    “I have built my own tag library and want all the tags to be of the form ==MISSING==. How do I do this?”
    Maybe you used unescaped XML-Tags?

    Thanks for sharing this!

    Reply
  3. Igor E. Poteryaev

    Running HSQDB Swing app should be done with a little different code snippet:

    org.hsqldb.util.DatabaseManagerSwing.main( ['-url', 'jdbc:hsqldb:mem:devDB'] as String[] )
    
    Reply
  4. Zachary Klein

    Excellent post! If it’s not too much trouble, it would be nice to have links to articles/documentation for each of these points (there already are links on a few of the questions). Makes it easier to brush up on anything that was unfamiliar.

    Um, I’ll just say I didn’t do quite as well as I’d like… But this ius a great resource for spotting my ‘learning gaps’! Thanks so much!

    Reply
  5. Irfan Ansari

    Very good collection of grails questions, though I didn’t do very well at the view side as mainly working with services.

    This also helps to brush up some of the things which is not covered by us during the project. Thanks a lot for sharing with the community.

    I’m not sure if few grails (some of them are Groovy truth) questions should be asked in an interview which is not straight forward. Sometime we assume that it will be handled by the groovy, but that’s not the case. for example

    def value = ‘2535353 ‘
    println value.isInteger()

    which returns true (please note the blank spaces in the value) and we wrongly assumed that it does understand it as integer so we don’t need to do anyting, but that’s not true. You have to specifically trim those spaces.

    Regards,
    Irfan

    Reply
  6. foxgem

    In this question:
    =======
    What are some things I need to be careful about when working with the Grails console?
    =======
    You said “So the code that you have typed in might get lost.”. I remembered the console can reload your code when it reload. And I did a simple experiment to verify it:
    1. grails console
    2. type some code in the console, such as ‘println ……’
    3. change your domain class file
    the the code you typed just now are reloaded in the console when reload happened.

    Anyway, this is a great post! And I will give my answer in my site ( in Chinese, http://www.groovyq.net )!

    Thank you!

    Reply
    1. Anil

      No, It always create all the tables if it’s not there. If any unique validation present then it will through error.

      Reply
  7. skurt

    and of course thanks for the questions, there is a lot which needs to be read again be myself😉
    The hint with a link to the point of documentation where the answer is explained will be fine, because otherwise it is like reading it, remember it but do not why it is like that. (the way we learned in school …😉 )

    Reply
  8. Pingback: link – Grails Interview Questions | Tomás Lin’s Programming Brain Dump « lepffm's Blog

  9. Pingback: link – Grails Interview Questions | Tomás Lin’s Programming Brain Dump « simple note

  10. Andrey

    Your question is: How do I inject a service to my domain class? From a servlet?
    I think it doesn’t make sense to inject service into domain, domain should be your ORM object and orm object should be injected into service but not vice verse. Otherwise I think you are doing something wrong.

    Reply
  11. Kruti

    What is the flash object? What other alternatives to the flash object can I use in my Grails application?

    What is the answer of this question?

    Reply
  12. Pingback: twitter bootstrap grails - Search Yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s