15 JavaScript Template Engines for Front-end Development

1

JavaScript libraries in no way declining, and the number is growing each day. When it comes to building JavaScript applications, it’s better to rely on templates than on full-scale libraries, because it enables us to have a much cleaner code base, and much better workflow to work with.

I wrote recently that you should try and build your own JavaScript libraries, when it’s time. But, template engines take a little more knowledge and understanding of the language you’re working with, so it’s better to depend on something pre-built, like any of the libraries in this list.

2

You can find a list of these on Wikipedia, it’s a nice comparison of template engines for a lot of web’s programming languages, but that list isn’t really focused on one particular language, and so I wanted to see how many templates engines I could gather up for JavaScript.

If you’ve been developing with JavaScript, you’ll know a handful of these, but you might also learn about some new ones that had not crossed your path until now. I had a lot of fun putting this list together, so I hope you will enjoy it.

ICanHaz.js

3

Very simple to use library for doing templating with Mustache.js, another templating engine that we will be looking at shortly. With ICanHaz.js you define your Mustache.js template snippets in script blocks of type=”text/html” and give them an “id” as a title for your snippet (which validates, btw).

Hogan.js

4

 

Twitter loves to be a part of the open-source community. You can use Hogan.js as a part of your asset packager to compile templates ahead of time or include it in your browser to handle dynamic templates.

Again, includes the same style that Mustache.js does, only delivers everything in a much more quick and efficient manner.

Handlebars.js

5

Handlebars.js is an extension to the Mustache templating language created by Chris Wanstrath. Handlebars.js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be.

mustache.js

6

It’s no doubt the most popular templating engine in the world right now, and almost every single library listed in this post is somehow related to, or inspired by Mustache. The documentation is very easy to read and understand, and highly recommended to use – works on pretty much every programming language that’s above average popularity level.

Transparency

7

Transparency is a client-side template engine which binds data to DOM. Write easily understandable, native HTML and everything is plain, good old JavaScript. No need to learn comprehensive templating syntax, it’s all transparent and easy to use.

doT.js

8

Just something for the Node.js community. doT.js is fast, small and has no dependencies. It was built in order to find the breaking point for speed and flexibility, and it certainly has achieved that feat.

Walrus

9

 

It aims to provide the essentials in such a compact manner that speed or templating doesn’t feel like an issue of its own, rather, Walrus is focused on making it easy for the developer to template his web apps.

Chibi.js

10

Chibi is all about saving bandwidth and time that it takes to present a template, it’s a little tiny JavaScript library that will help you better template your apps, and focus more on things like CSS, instead of using animations.

templayed.js

11

It’s the smallest templating engine you’ll come across, guaranteed. It’s also Mustache compilant and is very easy to use and understand, the official homepage features a great demo example that you can run and test code with, and on the GitHub page there are benchmarks and unit tests concluded, to show the efficiency of this library.

ECT

12

Just like templayed, ECT also has a demo setup on its homepage that you can play with and see live results. It’s built for speed, and claims to be the fastest templating engine for JavaScript. (built with CoffeeScript)

It’s compatible with Node.js, and has a very easy to understand syntax.

Pithy.js

13

An internal DSL for generating HTML in JavaScript. It’s great for small client-side projects, but not recommended to use for HTML heavy webpages.

T.js

14

T.js is a template engine that uses simple Javascript data structure to represent html/xml data.

Nunjucks

15

Built by Mozilla, Nunjucks is for those who need fast performance and flexibility that’s offered by the ability to extend the library with custom features and plugins.

Jade

16

Jade is designed primarily for server side templating in node.js, however it can be used in many other environments. It is only intended to produce XML like documents (HTML, RSS etc.) so don’t use it to create plain text/markdown/CSS/whatever documents.

Dust.js

17

Dust extends Mustache, and offers high quality performance compared to other solutions you might find in this list. Also includes a very easy to use, clean API.

JavaScript Template Engines

I didn’t try to provide samples, simply because a lot of these have live preview of samples available on their official documentation pages, and I don’t see the point in doing the same thing twice.

I hope that you were able to discover some new alternatives to use for your next project. I’m sure there are more of these out there, though these are the ones that made their presence felt the most.

Source

Other useful resources

http://jster.net/category/templating-engines

http://garann.github.io/template-chooser/

http://fiddle.rythmengine.com/

http://en.wikipedia.org/wiki/Comparison_of_web_template_engines

http://angular-ui.github.io/

http://html5boilerplate.com/

Building The User UI Using HTML5

We’ve just implemented the business services of our application, and exposed them through RESTful endpoints. Now we need to implement a flexible user interface that can be easily used with both desktop and mobile clients. After reading this tutorial, you will understand our front-end design and the choices that we made in its implementation. Topics covered include:

http://www.dreamstime.com/stock-photography-image35575712

  • Creating single-page applications using HTML5, JavaScript and JSON
  • Using JavaScript frameworks for invoking RESTful endpoints and manipulating page content
  • Feature and device detection
  • Implementing a version of the user interface that is optimized for mobile clients using JavaScript frameworks such as jQuery mobile

The tutorial will show you how to perform all these steps in JBoss Developer Studio, including screenshots that guide you through.

First, the basics

In this tutorial, we will build a single-page application. All the necessary code: HTML, CSS and JavaScript is retrieved within a single page load. Rather than refreshing the page every time the user changes a view, the content of the page will be redrawn by manipulating the DOM in JavaScript. The application uses REST calls to retrieve data from the server.

 ticket monster tutorial gfx single page app 58
Figure 1. Single page application

Client-side MVC Support

Because this is a moderately complex example, which involves multiple views and different types of data, we will use a client-side MVC framework to structure the application, which provides amongst others:

  • routing support within the single page application;
  • event-driven interaction between views and data;
  • simplified CRUD invocations on RESTful services.

In this application we use the client-side MVC framework “backbone.js”.

 ticket monster tutorial gfx backbone usage 58
Figure 2. Backbone architecture

Modularity

In order to provide good separation of concerns, we split the JavaScript code into modules. Ensuring that all the modules of the application are loaded properly at runtime becomes a complex task, as the application size increases. To conquer this complexity, we use the Asynchronous Module Definition mechanism as implemented by the “require.js” library.

Tip
Asynchronous Module Definition

The Asynchronous Module Definition (AMD) API specifies a mechanism for defining modules such that the module, and its dependencies, can be asynchronously loaded. This is particularly well suited for the browser where synchronous loading of modules incurs performance, usability, debugging, and cross-domain access problems.

Templating

Instead of manipulating the DOM directly, and mixing up HTML with the JavaScript code, we create HTML markup fragments separately as templates which are applied when the application views are rendered.

In this application we use the templating support provided by “underscore.js”.

Mobile and desktop versions

The page flow and structure, as well as feature set, are slightly different for mobile and desktop, and therefore we will build two variants of the single-page-application, one for desktop and one for mobile. As the application variants are very similar, we will cover the desktop version of the application first, and then we will explain what is different in the mobile version.

Setting up the structure

Before we start developing the user interface, we need to set up the general application structure and add the JavaScript libraries. First, we create the directory structure:

 ticket monster tutorial gfx ui file structure 67
Figure 3. File structure for our web application

We put stylesheets in resources/css folder, images in resources/img, and HTML view templates in resources/templatesresources/js contains the JavaScript code, split between resources/js/libs - which contains the libraries used by the application,resources/js/app - which contains the application code, andresources/js/configurations which contains module definitions for the different versions of the application – i.e. mobile and desktop. The resources/js/app folder will contain the application modules, in subsequent subdirectories, for models, collections, routers and views.

The first step in implementing our solution is adding the stylesheets and JavaScript libraries to the resources/css and resources/js/libs:

require.js
AMD support, along with the plugin:

  • text – for loading text files, in our case the HTML templates
jQuery
general purpose library for HTML traversal and manipulation

Underscore
JavaScript utility library (and a dependency of Backbone)

Backbone
Client-side MVC framework

Bootstrap
UI components and stylesheets for page structuring

Continue Reading

Top 10 Front-End Development Frameworks

As the Web matures and the range of mobile devices we use to access it rapidly grows, our jobs as web designers and developers get considerably more complicated.

A decade ago things were much simpler. Then, it was almost certain that most of our users were visiting our sites while sitting at their desk, looking at a large monitor. 960 pixels was more or less considered as a good width for a web page. Our main care was dealing with the dozen or so desktop browsers and jumping through a few extra browser hacks to support quirky old versions of Internet Explorer. But now, with the boom of handheld electronic devices in the last five to six years, everything has changed. We’ve seen the introduction of smartphones and tablets of all different sizes, eReaders, browsers on TVs and many others. The diversity is only going to increase each day.

Soon, more people will be accessing the Web on their mobile and alternate devices than on a desktop computer. In fact, already a significant number of people use their mobile phones as their only access to the Internet. That means it is important for us designers and developers to understand how to deal with this entire mobile world. And although, as of this writing, we haven’t entirely figured out how to make all the content we are accustomed to seeing at our desk provide an equally pleasing experience on our handheld devices, the technologies and tools for doing that get better.

One of the primary strategies we use when we deal with unknown viewport size is the so-called responsive web design. It’s a mechanism for providing custom layouts to devices based on the size of the browser window. By default, most browsers on small devices such as smartphones and tablets shrink a web page down to fit the screen and provide ways for zooming and moving around the page. Although it technically works, it is not such a great experience. The text is too small to read, the links too small to tap, and all that zooming and panning around is more or less distracting.

The technique of responsive web design is to serve a single HTML document to all devices by applying different style sheets based on the screen size in order to provide the most optimized layout for that device. For example, when the page is viewed on a large desktop browser, the content can be placed into multiple columns with normal navigation elements. But when that same page is viewed on a small smartphone screen, it appears in one column with large links for easy tapping. You can see just how responsive web design works at the Media Queries gallery site. Just open a design in your browser and then resize the window very narrow and very wide, and watch as the layout changes based on the window size.

So far we’ve seen that, at least for now, responsive web design is an sufficient solution for fighting with the growing device diversity, but what are the actual tools and technologies to implement it in our designs? Do we have to be web gurus to handle it or will just the essential skills we already have be enough? Are there any tools that can help us?

This is where front-end development frameworks come into play. Responsive web design is not so hard to implement but it can be a little bit tricky to make it all work on all targeted devices. Frameworks make this job easier. They allow you to create responsive, standard-compliant websites with minimum effort while at the same time keeping everything simple and consistent. Frameworks give you a lot of benefits such as speed and simplicity, consistency across different devices, and much  more. One of the most important advantages is that they are so easy to use that even a person with minimal knowledge can utilize them without any problem.

In brief, if you are serious in today’s web development then using frameworks is a must and not an option. Nowadays your site must be extremely flexible in order to satisfy different browsers, tablets, smartphones and a whole bunch of other handheld devices.

A front-end web development framework is simply a collection of production ready HTML/CSS/JavaScript components that we can use in our designs. There are many frameworks out there but some of them stand out from the crowd. For your facilitation below you will find outlined some of the most powerful and popular frameworks available today. Bear in mind that these are not just CSS grids or so, but instead full-featured front-end development frameworks.

1. Bootstrap

Bootstrap is definitely the most popular and widely used framework, nowadays. It’s a beautiful, intuitive and powerful web design kit for creating cross browser, consistent and good looking interfaces. It offers many of the popular UI components with a plain-yet-elegant style, a grid system and JavaScript plugins for common scenarios.

It is built with LESS and consists of four main parts:

  • Scaffolding – global styles, responsive 12-column grids and layouts. Bear in mind that Bootstrap doesn’t include responsive features by default. If your design needs to be responsive you have to enable this functionality manually.
  • Base CSS – this includes fundamental HTML elements like tables, forms, buttons, and images, styled and enhanced with extensible classes.
  • Components – collection of reusable components like dropdowns, button groups, navigation controls (tabs, pills, lists, breadcrumbs, pagination), thumbnails, progress bars, media objects, and more.
  • JavaScript – jQuery plugins which bring the above components to life, plus transitions, modals, tool tips, popovers, scrollspy (for automatically updating nav targets based on scroll position), carousel, typeahead (a fast and fully-featured autocomplete library), affix navigation, and more.

Bootstrap is already powerful enough to empower any web interface. But in order to make more use of it and making the development process easier, you can find plenty of tools and resources that complement it. Some of them are listed below:

  • jQuery UI Bootstrap - an awesome resource for jQuery and Bootstrap fans that combines the power of both. It brings nicely the slickness of Bootstrap to jQuery UI widgets.
  • jQuery Mobile Bootstrap Theme - similar to the jQuery UI theme above, this is a theme built for jQuery Mobile. It is a handy resource if you have a web front-end built with Bootstrap and want to offer a similar look for mobile.
  • Fuel UX - this extends Bootstrap with additional lightweight JavaScript controls. It’s easy to install, customize, update, and optimize.
  • StyleBootstrap.info - Bootstrap has its own customizer but StyleBootstrap is a more detailed one with color pickers and the ability to style each component differently
  • BootSwatchr - a Bootstrap theme roller that shows the immediate results of your changes. For every generated style, the application generates a unique URL in case you want to share it with others or return and edit anytime later.
  • Bootswatch - a nice set of free themes for Bootstrap.
  • Bootsnipp - a good collection of design elements and HTML snippets for Bootstrap. It offers also form and button builders.
  • LayoutIt - drag and drop interface builder based on the elements and components of Bootstrap. It helps you to compose your design visually by placing and arranging different elements into your layout via drag and drop and then allows you to edit their properties. You get the base code and then expand it. Simple and easy.

2. Fbootstrapp

Fbootstrapp is based on Bootstrap and gives you the same functionality for Facebook iframe apps and designs. It includes base CSS and HTML for all standard components like typography, forms, buttons, tables, grids, navigation, and more, styled in the typical Facebook look and feel.

3. BootMetro

BootMetro is a framework inspired by the Metro UI CSS, which is built on top of Bootstrap, for creating Metro/Windows 8-styled websites. It includes all Bootstrap’s features plus some additional extras like tiled pages, an application bar, and more.

4. Kickstrap

Simply put, Kickstrap is a kind of Bootstrap on steroids. It uses Bootstrap as its base and extends it with many apps, themes and extras. This makes the framework a complete kit for building websites without the need to install anything. Just put it in your site and you are ready to go.

Apps are just bundles of JavaScript and CSS files that run together as a package after your page has finished loading. Some of the apps included by default are Knockout.js, Retina.js, Firebug Lite, and Updater. And you can add many more.

Themes give you the ability to differentiate from most Bootstrap websites’ standard look and feel.

Extras are fan-created additions to extend Bootstrap UI library. They usually use the same or similar syntax.

5. Foundation

Foundation is a powerful, feature-rich, responsive front-end framework. With Foundation you can quickly prototype and build websites or apps that work on any kind of device, with tons of included layout constructs, elements and best practices. It’s built with mobile first in mind, utilitizes semantic features, and uses Zepto instead of jQuery in order to brings better user experience and faster performance.

Foundation has a 12-column flexible, nestable grid powerful enough to let you create rapidly multi-device layouts. In terms of features it provides many. There are styles for typography, buttons, forms, and various navigation controls. Many useful CSS components are provided like panels, pricing tables, progress bars, tables, thumbnails, and flex video that can scale properly your video on any device. And, of course, JavaScript plugins including dropdowns, joyride (a simple and easy website tour), magellan ( a sticky navigation that indicates where you are on the page), orbit (a responsive image slider with touch support), reveal (for creating modal dialogs or pop-up windows),  sections (a powerful replacement for traditional accordions and tabs), and tooltips.

The framework also offers many useful add-ons.

  • Stencils – all UI elements available in Foundation in a form of Omnigraffle stencils and vector PDFs for building wireframes and mock-ups faster and more easily.
  • HTML Templates – handy, ready to go layouts for you to quickly start from and build on. To use them you simply grab the code and drop it between the <body> tags of your page.
  • Icon Fonts – these are custom icon sets of pictographic icons stored in a handy web font.
  • SVG Social Icons – a set of resolution-independent social icons.
  • Responsive Tables -  the mechanism of Foundation’s responsive tables is to take the first column and “pin” it to the left of the table, thus allowing you to scroll the other columns under it.
  • Off-Canvas Layouts – these layouts allows you to keep content or navigation on mobile devices hidden until either a larger screen size allows it to be visible or a user takes action to expose it. And when the last happens the content or navigation slides into view.

As you can see, Foundation is like a treasure-house for web developers/designers. And in order to get only what you need you can use the customizer to build your custom download.

6. GroundworkCSS

GroundworkCSS is a new, fresh addition to the front-end frameworks family. It’s a fully responsive HTML5, CSS and JavaScript toolkit built with the power of Sass and Compass which gives you the ability to rapidly prototype and build websites and apps that work on virtually any device.

It offers an extremely flexible, nestable, fraction-based, fluid grid system that makes creating any layout possible. GroundworkCSS has some really expressive features like tablets and mobile grids which maintain the grid column structure instead of collapsing the grid columns into individual rows when the viewport is below 768 or 480 pixels wide. Another cool feature is a jQuery ResponsiveText plugin which allows you to have dynamically sized text that adapts to the width of the viewport: extremely useful for scalable headlines and building responsive tables.

The framework includes a rich set of UI components like tabs, responsive data tables, buttons, forms, responsive navigation controls, tiles (a beautiful alternative to radio buttons and other boring standard form elements), tooltips, modals, Cycle2 (a powerful, responsive content slider), and many more useful elements and helpers. It also offers a nice set of vector social icons and a full suite of pictographic icons included in FontAwesome.

To see the framework in action you can use the resizer at the top center of the browser window. This way you can test the responsiveness of the components against different sizes and viewports while exploring the framework’s features.

GroundworkCSS is very well documented with many examples, and to get you started quickly the framework also provides you with several responsive templates. The only thing I consider as a weakness is the missing of a way to customize your download.

7. Gumby

Gumby is simple, flexible, and robust front-end framework built with Sass and Compass.

Its fluid-fixed layout self-optimizes the content for desktop and mobile resolutions. It support multiple types of grids, including nested ones, with different column variations . Gumby has two PSD templates that get you started designing on 12 and 16 column grid systems.

The framework offers feature-rich UI Kit which includes buttons, forms, mobile navigation, tabs, skip links, toggles and switches, drawers, responsive images, retina images, and more. Following the latest design trends the UI elements have Metro style flat design but you can use Pretty style with gradient design too, or to mix up both styles as you wish. An awesome set of responsive, resolution independent Entypo icons, for you to use in your web projects, is completely integrated into the Gumby Framework.

Gumby has also a very good customizer with color pickers which helps you to build your custom download with ease.

8. HTML KickStart

HTML KickStart is a HTML5, CSS and jQuery-powered toolkit for easily creating any type of layout. It provides clean, standards-compliant and cross-browser mark-up.

The framework has styles for grids, typography, forms, buttons, tables or lists and cross-browser web elements like a JavaScript slideshow, tabs, breadcrumb navigation, menus with sub-menus, tooltips, and more.

You can use 99Lime UIKIT which has all the UI elements of HTML KickStart ready to be used in your wireframes.

9. IVORY

IVORY is a lightweight, simple and powerful framework that can handle responsive layouts from 320px to 1200px widths. It is packed with 12-column fluid width grid, styles for typography and some essential UI components like buttons, toggle-switches, accordions, tabs, tooltips, and more.

IVORY is a perfect choice when you need a simple and flexible, multi device solution, and your design doesn’t requires extra functionality which other frameworks offer.

10. Kube

Lastly, if you need a solid, yet simple base without needless complexity and extras, for your new project, Kube can be the right choice. Kube is a minimal, responsive and adaptive framework with no imposed styling which gives you the freedom to create. It offers basic styles for grids, forms, typography, tables, buttons, navigation, and other stuff like links or images.

The framework contains one compact CSS file for building responsive layouts with ease and two JS files for implementing tabs and buttons in your designs. If you are looking for maximum flexibility and customization, you can download developer version which includes LESS files, with variables, mixins and modules.

Sources 1, 2

Converting Grails Applications to Plugins and vice versa

I was in London last week on vacation with my family and was lucky that there was a London GGUG meetup during my visit. David Dawson discussed modularizing Grails applications by refactoring them into multiple plugins (you can see the video of his talk here). One thing that he mentioned was the idea of plugins that can be run like standalone applications since the structures of Grails applications and plugins are so similar, and I thought it would be interesting to look at the process of converting an application to a plugin or a plugin to an application.

The approaches I’ll discuss here include a lot of bias on my part about how I like to create apps and plugins, so YMMV. I also won’t go into partial conversions since David covered this well in his talk.

So to convert an application to a plugin, the general workflow would be something like

  • Create the plugin descriptor, FooGrailsPlugin.groovy. The easiest way to do this is to rungrails create-plugin pluginname and copy the generated file from there
  • delete everything from application.properties except the app.grails.versionproperty
  • if you have jars in the lib directory that are available in a Maven repo, delete them and replace with BuildConfig.groovy dependencies
  • change any plugin and jar dependencies that are needed for development and testing but not when the plugin is installed to not be exported, by adding export = false
  • If you need the _Install.groovy_Uninstall.groovy, or _Upgrade.groovy scripts (you probably don’t) grab those from the dummy plugin from step 1 (but delete any you don’t need, they’re all optional)
  • delete ApplicationResources.groovy if you aren’t using it and don’t depend on resources plugin
  • move code from BootStrap.groovy init() toFooGrailsPlugin.doWithApplicationContext and/orFooGrailsPlugin.doWithDynamicMethods and destroy() to FooGrailsPlugin.onShutdown, and delete BootStrap.groovy
  • add a dependency for the release plugin in BuildConfig.groovy
  • delete everything but the log4j configuration from Config.groovy
  • delete UrlMappings.groovy unless you have exported mappings; only keep the added ones
  • move bean definitions from resources.groovy to FooGrailsPlugin.doWithSpringand delete resources.groovy
  • delete grails-app/i18n message bundle files unless you added messages; only keep the added ones
  • delete everything from grails-app/views that you don’t use (in particular error.gsp,index.gsp, and layouts/main.gsp)
  • delete everything from web-app that you don’t use (including WEB-INF xml and tld files)
  • now would be a great time to write those tests you’ve been meaning to get to
  • create one or more test applications to install the plugin into to ensure that it works as a plugin; consider scripting this
  • write documentation for how to use the plugin; at a minimum a README file, but Grails gdoc files would be much better (run grails doc --init to get started)

Converting a plugin to an application is similar, except for the most part reversed:

    • Create a dummy application with grails create-app appname to copy missing files from
      • Move BootStrap.groovyConfig.groovyUrlMappings.groovy, andApplicationResources.groovy into grails-app/conf, merging if needed
      • Move resources.groovy into grails-app/conf/spring
      • Move message bundle files to grails-app/i18n, merging if needed
      • Move missing GSPs to grails-app/views
      • Move static resources from web-app
      • Move xml and tld files from web-app/WEB-INF
    • Move code from FooGrailsPlugin.doWithApplicationContext andFooGrailsPlugin.doWithDynamicMethods to BootStrap.groovy init(), and code from FooGrailsPlugin.onShutdown to destroy()
    • Move bean definitions from FooGrailsPlugin.doWithSpring to resources.groovy
    • Delete the plugin descriptor
    • Restore missing properties in application.properties
    • Delete the _Install.groovy_Uninstall.groovy, and _Upgrade.groovy scripts
    • Remove the dependency for the release plugin from BuildConfig.groovy
    • Now would be a great time to write those tests you’ve been meaning to get to
    • If you make changes in the plugin’s doWithWebDescriptor, run grails install-templates and add them to src/templates/war/web.xml
    • If you add custom artifacts, or were supporting development-environment code or config changes in onChange and/or onConfigChange, these aren’t directly doable in an application. Use the pluginator plugin for these, and also for dynamic web.xml changes that require runtime logic

I’ve probably skipped a few steps and definitely omitted a lot of detail, but this should cover most of the process for each type of conversion.

Polymorphic Association Mapping with Any Relationship in Hibernate

Polymorphic association, supported by Hibernate, is the solution of such mapping requirement as an instance of entity needs to be associated with one of multiple possible entities. This can be implemented with Any relationship. In this relationship, the table holding the relationship would have two columns for relationship management. One to identify the primary key value of record being associated and another to identify the table to which the associated record belongs.

As the relationship is between one table to multiple other tables, foreign key relationship would not exist in database.One such real life example is sale scenario, where a vehicle seller sells truck and bus both. The requirement is to design sales system to manage the data of vehicles being sold. As bus and truck are completely different vehicles, a developer might design the system as mentioned in following class and ER diagram.

ax

 

bx

 

In this case, during each sale transaction, one vehicle will be sold. This vehicle can either be bus or truck. On the database level, SaleTransaction table would have two attributes vehicleType and vehicleId to manage the relationship. Vehicle type would represent whether corresponding vehicleId belongs to bus or truck.

As the relationship is between one table to multiple tables, foreign key constraint wouldn’t exist in the database layer.

Let us see the implementation of this scenario.

Class maintaining the relationship between SaleTransaction to Bus and Truck entity

SaleTransaction.java

 

package com.anytest;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;

import lombok.Data;

import org.hibernate.annotations.Any;
import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.MetaValue;

@Data
@Entity
public class SaleTransaction {

	@Id
	@GeneratedValue
	private Long Id;
	private Date saleDate;
	private Long salePrice;

	 @Any (metaColumn = @Column(name = "vehicleType"))
	 @AnyMetaDef(idType = "long", metaType = "string",
	 metaValues = {
	 @MetaValue(targetEntity = Bus.class, value = "bus"),
	 @MetaValue(targetEntity = Truck.class, value = "truck")
	 })
	@Cascade( { org.hibernate.annotations.CascadeType.ALL})
	@JoinColumn(name = "vehicleId")
	private Vehicle vehicle;

	public SaleTransaction() {
	}

	public SaleTransaction(final Date saleDate, final Vehicle vehicle,final Long salePrice) {
		this.saleDate = saleDate;
		this.vehicle = vehicle;
		this.salePrice=salePrice;
	}
}

In this case, the developer has defined that SaleTransaction would be managing the relationship using vehicleType and vehicleId columns in database. If the transaction is of bus sale then vehicleType column in SaleTransaction table would be ‘bus’ and vehicleId would be the value of primary key of corresponding bus. In the same way, if the transaction is of Truck sale then the vehicleType column in SaleTransaction would be ‘truck’ and vehicleId would be the value of primary key of corresponding truck.

Query to create table structure in H2 database

 

create table Bus (
    id bigint generated by default as identity,
    acAvailable boolean not null,
    buyingPrice bigint,
    engineCapacity bigint,
    modelNo varchar(255),
    seatCount integer not null,
    primary key (id)
);
create table SaleTransaction (
    Id bigint generated by default as identity,
    saleDate timestamp,
    salePrice bigint,
    vehicleType varchar(255),
    vehicleId bigint,
    primary key (Id)
);
create table Truck (
    id bigint generated by default as identity,
    buyingPrice bigint,
    engineCapacity bigint,
    modelNo varchar(255),
    trunkVolumeCapacity bigint,
    primary key (id)
);

Vehicle Interface

package com.anytest;

public interface Vehicle {

		Long getBuyingPrice();
		String getModelNo();
		Long getEngineCapacity();
}

Bus Class

package com.anytest;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import lombok.Data;

@Data
@Entity
public class Bus implements Vehicle {

	@Id
	@GeneratedValue
	Long id;
	Long buyingPrice;
	String modelNo;
	Long engineCapacity;
	int seatCount;
	boolean acAvailable;

	public Bus(){}

	public Bus(final Long buyingPrice, final String modelNo, final Long engineCapacity, final int seatCount, final boolean acAvailable)
	{
		this.buyingPrice=buyingPrice;
		this.modelNo=modelNo;
		this.engineCapacity=engineCapacity;
		this.seatCount=seatCount;
		this.acAvailable=acAvailable;
	}
}

Truck Class

package com.anytest;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import lombok.Data;

@Data
@Entity
public class Truck implements Vehicle {

	@Id
	@GeneratedValue
	Long id;
	Long buyingPrice;
	String modelNo;
	Long engineCapacity;
	Long trunkVolumeCapacity;

	public Truck(){}

	public Truck(final Long buyingPrice, final String modelNo, final Long engineCapacity, final Long trunkVolumeCapacity)
	{
		this.buyingPrice=buyingPrice;
		this.modelNo=modelNo;
		this.engineCapacity=engineCapacity;
		this.trunkVolumeCapacity=trunkVolumeCapacity;
	}
}

hibernate.cfg.xml – hibernate configuration file

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.driver_class">org.h2.Driver</property>
		<property name="hibernate.connection.url">jdbc:h2:~/anyMappingDemo</property>
		<property name="hibernate.connection.username">sa</property>
		<property name="hibernate.connection.password"></property>
		<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>

		<!-- JDBC connection pool (use the built-in) -->
		<!--<property name="hibernate.hbm2dll.auto">create-drop</property> -->
		<property name="connection.pool_size">1</property>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>

		<mapping class="com.anytest.Bus"></mapping>
		<mapping class="com.anytest.Truck"></mapping>
		<mapping class="com.anytest.SaleTransaction"></mapping>

	</session-factory>
</hibernate-configuration>

HibernateInterface – Class to deal with Hibernte interaction

package com.anytest;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

@SuppressWarnings("deprecation")
public class HibernateInterface {

	final static Configuration CONFIGURATION = new Configuration().configure();
	final static SessionFactory SESSION_FACTORY = CONFIGURATION.buildSessionFactory();
	static
	{
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

			@Override
			public void run() {
				if(SESSION_FACTORY!=null && !SESSION_FACTORY.isClosed())
				{
					SESSION_FACTORY.close();
				}

			}
		}));
	}

	public static void saveEntities(final Object entity)
	{
		final Session session = SESSION_FACTORY.openSession();
		session.beginTransaction();
		try {
			session.saveOrUpdate(entity);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		finally{
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public static List<Object> getRecordsOfType(final Class<?> classObject)
	{
		final Session session = SESSION_FACTORY.openSession();
		try {
			 List<Object> resultList = session.createCriteria(classObject).list();
			 resultList.toString();
			 return resultList;
		}
		finally{
			session.close();
		}
	}

	public static int exectueQuery(final String hqlQuery)
	{
		int effectedRecords=0;
		final Session session = SESSION_FACTORY.openSession();
		session.beginTransaction();
		try {
			effectedRecords=session.createQuery(hqlQuery).executeUpdate();
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		finally{
			session.close();
		}
		return effectedRecords;
	}
}

PaymentActoinPerfomer – Class to perform Implicit Polymorphism test

package com.anytest;

import java.util.Date;
public class ActionPerformer {

	public static void main(String[] args) {

		final Bus bus = new Bus(600000L, "ABCDBusModel", 100L, 35, true);
		final Truck truck = new Truck(700000L, "ABCDTruckModel", 300L, 30000L);

		final SaleTransaction busSaleTransaction = new SaleTransaction(new Date(), bus,650000L);
		final SaleTransaction truckSaleTransaction = new SaleTransaction(new Date(), truck,780000L);

		HibernateInterface.exectueQuery("delete from com.anytest.SaleTransaction");
		HibernateInterface.exectueQuery("delete from com.anytest.Vehicle");

		HibernateInterface.saveEntities(busSaleTransaction);
		HibernateInterface.saveEntities(truckSaleTransaction);

		System.out.println("SaleTransaction records =" + HibernateInterface.getRecordsOfType(SaleTransaction.class));
	}

}

In this scenario, the developer has set cascade type as ALL. So while saving the transient entry of busSaleTransaction and truckSaleTransaction, hibernate at first stores the transient records of Bus into BUS table or Truck into TRUCK table and then corresponding transaction entry in SaleTransaction table.

This behaviour can be seen in the query fired hibernate. While saving bus transaction hibernate fires following query -

Hibernate:
    insert
    into
        Bus
        (id, acAvailable, buyingPrice, engineCapacity, modelNo, seatCount)
    values
        (null, ?, ?, ?, ?, ?)
Hibernate:
    insert
    into
        SaleTransaction
        (Id, saleDate, salePrice, vehicleType, vehicleId)
    values
        (null, ?, ?, ?, ?)

While retrieving the records from SaleTransaction table, hibernate fires the query on SaleTransaction table. Then depending on the value of vehicleType hibernate fires the query in Bus or Truck table to get the associated records. In this Sales scenario hibernate fires following queries to get SaleTransaction records -

 

Hibernate:
    select
        this_.Id as Id1_1_0_,
        this_.saleDate as saleDate2_1_0_,
        this_.salePrice as salePric3_1_0_,
        this_.vehicleType as vehicleT4_1_0_,
        this_.vehicleId as vehicleI5_1_0_
    from
        SaleTransaction this_
Hibernate:
    select
        bus0_.id as id1_0_0_,
        bus0_.acAvailable as acAvaila2_0_0_,
        bus0_.buyingPrice as buyingPr3_0_0_,
        bus0_.engineCapacity as engineCa4_0_0_,
        bus0_.modelNo as modelNo5_0_0_,
        bus0_.seatCount as seatCoun6_0_0_
    from
        Bus bus0_
    where
        bus0_.id=?
Hibernate:
    select
        truck0_.id as id1_2_0_,
        truck0_.buyingPrice as buyingPr2_2_0_,
        truck0_.engineCapacity as engineCa3_2_0_,
        truck0_.modelNo as modelNo4_2_0_,
        truck0_.trunkVolumeCapacity as trunkVol5_2_0_
    from
        Truck truck0_
    where
        truck0_.id=?

The result of retrieving all sales transactions by firing query on SaleTransaction.class is as following -

SaleTransaction records =[SaleTransaction(Id=5, saleDate=2013-10-27 18:35:09.088, vehicle=Bus(id=3, buyingPrice=600000, modelNo=ABCDBusModel, engineCapacity=100, seatCount=35, acAvailable=true), salePrice=650000),
SaleTransaction(Id=6, saleDate=2013-10-27 18:35:09.088, vehicle=Truck(id=3, buyingPrice=700000, modelNo=ABCDTruckModel, engineCapacity=300, trunkVolumeCapacity=30000), salePrice=780000)]

Limitation of Any Hibernate Mapping

Any relationship cannot be implemented as bidirectional association. It will be unidirectional relationship managed by entity holding the relationship data.

The second limitation of Any relationship is that one can not set foreign key relationship on database layer to manage integrity.

The working project can be accessed from here in github.

I hope this article helped you to understand polymorphic association implementation in hibernate in a better way. Do share your experience about the article and way you are planning to use polymorphic association in your application.

I will come with the different new topics in future for sure. If you have any questions, please write it in the comments section.

Source

Another Links

http://jpaobjects.sourceforge.net/m2-site/main/documentation/docbkx/html/user-guide/ch04s09.html

http://www.techques.com/question/1-217831/How-to-use-Hibernate-@Any-related-annotations

Top 20 Features of Code Completion in IntelliJ IDEA

In this article I would like to highlight the top features of code completion in IntelliJ IDEA, which make coding for Java incredibly productive. Everyone agrees that completion is a number one feature for any IDE. It predicts what you are trying to type and completes it for you, even if you don’t know exactly the name of particular class, member or any other resource.

The secret, why code completion in IntelliJ IDEA is so profound, is that IntelliJ IDEA really understands your code, as well as the context you stay in. Here I will make a short overview of the most important features, which make IntelliJ IDEA unique among other Java IDEs.

Instant completion

The first one and probably the most impressive feature I would like to highlight is instant completion. Unlike other IDEs, IntelliJ IDEA provides it everywhere, not only when you are trying to access a member of a class. Just type a first letter of a word, and IntelliJ IDEA will instantly start suggesting the most relevant options, which would be appropriate for current place. This means you don’t need to call completion explicitly.

To get the idea, how efficient Instant completion is, watch demo.

Type-aware completion

Another feature, which also breaks down common code completion approach, is so called Smart completion. You might already know, that there are more than one type of completion exist in IntelliJ IDEA. These are Basic completion ⌘Space and Smart completion ⌘⇧Space.

When you call Smart completion, it filters suggestion list and shows only classes, variables, fields and methods of the type, expected in the context. This improves performance very much and keeps you out of possible mistakes. After you try it, promise, you will miss it all the time.

Static fields and methods

Just as I said, IntelliJ IDEA always tries to be a step ahead of you. If you don’t remember class name with static member, which you need, just start typing the name of the member and call completion twice. It will provide correct completion, and even offer to import the member statically, if you call Intention action ⌥⏎.

Once again, if you use Smart completion, it will offer only members of expected type.

Chain completion

Next feature, which makes you even more productive, is Chain completion. If you need to type a chain like getModule().getProject(), just call Smart completion twice. In that case IntelliJ IDEA will scan variables, fields and methods, visible from the context, and offer you a chain, which satisfies expected type.

As you might know, recently there was a plugin for Eclipse Juno, called Code Recommenders. This is quite interesting plugin, which also claims to provide a kind of chain completion. However, it works in a different way. While Code Recommenders suggests only chains of Eclipse SDK APIs classes, IntelliJ IDEA provides chains of any classes from your code.

Data flow analysis

The reason, is why IntelliJ IDEA is called the most intelligent Java IDE, is that it has many aspects of any feature, that reveal depending on the results of analysis of your code. Data flow analysis is an example. IntelliJ IDEA analyses data flow to guess the type of a variable in runtime and provide a completion, based on this type, adding class casts automatically.

Constants completion

Many API provide constants of primitive types instead of enum types. IntelliJ IDEA is aware of such constants in the project and suggests them in completion, what is very helpful, if you are dealing with legacy APIs.

Super completion

You might noticed, how it is deadly boring to manually type a super constructor having many arguments. IntelliJ IDEA understands you and provides completion for this case too.

Statements completion

Another brilliant feature of IntelliJ IDEA is Complete statement ⌘⇧⏎, which helps you complete the rest part of a statement. It automatically adds missing parentheses, brackets, braces and apply necessary formatting.

You might consider this a minor feature, but you will be surprised, how much time it can save, when you get used to it.

To see how it works, try to type “if” and click ⌘⇧⏎. You can also use it when you select item from suggestion list.

Parameter info

I believe, that pretty number of IDEs, provide info on expected parameters, when you call a method or a constructor. However the way, how they provide it, does matter.

IntelliJ IDEA shows parameter info for every overloaded method or constructor, and highlight the best match for the parameters already typed. This helps you choosing between overloaded options and compare your input with expectation.

If you don’t know, Parameter info may be also shown on demand, by clicking ⌘P.

Quick definition

One more feature, you might not know, is Quick definition ⌘⇧I. It raises a popup with definition for every item from suggestion list. In many cases definition info is more useful than even documentation, especially when you are not sure, which method is to use.

Exclude from completion

I’m sure, everyone at least once faced the situation, when some class, that you never use, is constantly suggested in completion (e.g. from com.sun or java.awt packages).

IntelliJ IDEA can help you exclude such class or even the whole package from completion. Just callIntention ⌥⏎ on an item and confirm exclusion. You can always turn it back in Settings.

Injected languages

Next feature I want to mention, is much more than only about code completion. I hope to cover it deeply in a separate article, but in the meanwhile, I will describe the aspects of this feature, which relate to code completion.

Language injection is a feature of IntelliJ IDEA that brings advanced code assistance for expressions within String literals in Java code. This expression may contain SQL, JPQL, XPath expression, HTML, CSS, JavaScript fragment or any other language.

Before IntelliJ IDEA provides code completion for such expression, you must specify it’s language. You can do it by calling Intention action ⌥⏎ on a String literal. After that you will be able to use code completion, as it was not a String literal.

For instance, if you define a datasource in IntelliJ IDEA, you will get code completion for SQL expressions, based on actual tables scheme. The IDE analyzes all the project files to provide advanced completion for every supported language.

Completion with Tab

One more feature, that makes life easier, is Сompletion with Tab. If you select an item from suggestion list by clicking ⇥, it will overwrite identifier at the caret, instead of just insert. This is helpful if you edit a fragment of an identifier, such as name of a file.

Negating boolean results

Not everyone knows, that if you select boolean item from suggestion list with !, IntelliJ IDEA automatically adds negation operator to the result. This is an additional way to approve completion.

Middle matching

Another feature, which is quite impressive and efficient is Middle matching. It means, you can type an an identifier not even from the beginning. IntelliJ IDEA will still offer you correct completion. This is helpful and improves your performance significantly, especially if you remember only a part of the name.

Case sensitivity settings

As you might know, the common approach in code completion implies using camel humps to match your input with class names. Thus you need to enter at least one uppercase letter to give an IDE a clue, which class you want to have completed. IntelliJ IDEA advances this approach with case-insensitive completion. This means you don’t need to press ⇧ for each camel hump to get completion. Twice as less keys every day.

By default IntelliJ IDEA is sensitive to the first letter only. You can change it in Settings.

Completion for properties, file names, resources, etc.

One more feature, someone may not know is completion within String literals, recognized as property names, file names, resources, etc.

Class name completion in non-Java files

Additionally to Java, IntelliJ IDEA provides code completion for fully-qualified class names in other resource files, such as property files, XML, etc.

Completion in other places

One of the nicest things about completion in IntelliJ IDEA, you will hardly find in other IDEs, is that, it works not only in the editor, but also in Evaluate Expression, Watches, file choosers, search inputs and many other elements over the IDE.

Code completion in Evaluate expression and Watches tools is absolutely invaluable, when you evaluate state of your application while debug.

This may be useful, if you have hard time finding particular item in suggestion list.

Summary

I hope this article will you help better understand how code completion works in IntelliJ IDEA, just as benefits it gives for a developer.

Please also use Help → Productivity Guide to see how many completion types you use and how much time IntelliJ IDEA saves for you every day.

Continue reading →

What I wish I knew about Grails before my first Grails Project

Introduction
A year ago, I did my first official Grails project. Since it was a short term project, I felt I had to start with both feet in; working on the actual business requirements for the project immediately. Looking back at the project, that wasn’t the right decision. In reviewing the project, I came up with a checklist of what I would have done differently.

As I put this list together, most of it seems common sense to me now; a lot of this is true for anyone adopting a new technology stack for a project. While this can be applied to other technology stacks, my goal is to list out specifics with Grails. I’m sure my list is incomplete, and would love comments from others to add to this list.

Pick an IDE suited for Groovy and Grails
I used Eclipsed Based, Spring Tool Suite (STS), and I was heavily disappointed. The Groovy support was limited. I was also on a Mac OSX and you combine the slow file system of the Mac with STS and I spent more time waiting for the please waitcursor to go away, than actually develop code. Since I was on this project part-time, I thought I couldn’t justify getting IntelliJ; that was a mistake. Being very familiar with Eclipse for my Java development, the transition to STS was super easy, however, it didn’t really help me write Groovy/Grails applications to the level I was expecting. The limited auto-complete for Groovy and the slowness of the application was unbearable; big disappointment.

The more your IDE supports Groovy, the more you will write true Groovy Syntax. With STS I stayed with static typing as much as possible, so the IDE would be able to handle code completion and compile errors. With IntelliJ, I’m sure I would have embraced more dynamic typing.

Learn Groovy w/out Grails
Take at least 2 days and learn Groovy w/out Grails, GORM, or any other addition to the technology stack. Your first Groovy classes will end up being Java written in Groovy. You will most likely fail to take advantage of all the cool features of Groovy. I have used closures with all of my functionality programming experience, but I hadn’t used them in Groovy before; and it has been a while, since I spend most of my work day using Java. Your going to want to throw away your first code anyway, so pick a simple problem and write Groovy. I would take a complex algorithm you wrote in Java, that included nested classes, anonymous classes, reading and writing a markup language (HTML or XML) and rewrite it in Groovy. Making sure you take advantage of closures, native lists or maps, groovy markup, and dynamic typing.

Follow a Difference from Java article, such as codehaus, and work through an example hitting on these concepts. Be sure to include closures, native lists & maps, safe navigation, and dynamic typing. As many that use Groovy, you will soon wish a lot of these conventions were available in Java. Something as simple as safe navigation is such a simple concept that saves a lot of typing and makes code more readable. Again, take the time to learn Groovy, so you take advantage of writing good Groovy code. Since your initial code will look more like Java than Groovy, give yourself an assignment so you can throw the code away, when you are done. You will probably want to.

Groovy Gotchas
This is a short list of Groovy features I liked, but at the same time, caused me issues. It is key areas to why I believe it is important to learn and understand Groovy as a language before you add in the concepts of Grails, GORM, and other features. Here is a list of a few things that I keep in mind, while writing Groovy code.

  • Map Constructor – The map constructor is great when it comes to code compactness. However, what happens when you mistype an argument name or you include an argument that doesn’t exist, groovy treats it as a no-op. I had to track down a lot of failed initializations because I had a typo. I am also a big fan of invariants. I like my options that require fields to be initialized, to have them initialized. Since the map-constructor just calls all of the setters for you, the instance can have an invalid state; especially if you have a typo.
  • Map Key – implied quotes. I’m not a big fan of language inconsistencies. So to have the convenience of the key being a string w/out quotes annoys me. Be sure to learn the language nuances so they don’t trip you up. I have never been a fan of Java ‘+’ for Strings. I would rather have the language be consistent and allow for operator overloading for all objects, not just for the + operator for Strings only.

Grails
Scaffolding
Just like you should spend a couple of days learning Groovy w/out Grails, you should spend a couple of days learning Grails w/out developing for your project. The automated scaffolding can be used as part of learning Grails, but I shouldn’t be used for your production code. Also, I would rather have you auto generate the scaffolding and use/tweak it when learning Grails. Once you start building your actual application, start from scratch. Or, better yet, customize the scaffolding generation and then use it to build all of your web pages. In any case, there is a lot of power with the scaffolding (dynamic and generated). Just don’t generate it and then try to tweak it to your desired state. You will end up with a lot of dead code, and code that doesn’t really fit your application — at least that is what happened to me.

GORM
I have used Hibernate/JPA for 8+ years. I am a big fan of Hibernate, and appreciate all that I can do with it. I will use various different fetching strategies as needed; one of my favorite is sub-select. However, you need to know your your session life-cycle and use cases to build your application correctly. GORM is great, it does a lot of the stuff for you. The dynamic finders (up to 2 arguments) are fantastic. The amount of boiler plate code using Hibernate with GORM is so much less than writing Hibernate or JPA in Java. That being said, if you are new to Hibernate, GORM will make things easier, but it will also make it harder to understand how and why everything is working.

If you have experience with Hibernate in Java, I would recommend taking a simple object relationship you built in Hibernate/JPA in Java and apply it to GORM/Grails.

This is also where I feel the dynamic scaffolding shines. While I work on a complete technology stack, my expertise is more in the persistence tier. it is also how I think about the application; how am I going to store the data is what I want to work on first. Let Grails help you get that right, before you start working on any of our presentation. Write your GORM entities and relationships, your unit tests, and then use the default scaffolding to visualize use it to see if it “makes sense”. You can work on your transaction boundries, lazy/eager associations, fetching strategies w/out focusing on any of the UI.

This is the one area, I’m very happy with how I developed the initial application. I focused on the persistence tier and tested/used it before building any of the UI. That is because, how I think through a problem domain. Grails/GORM worked perfectly for me. I just wished I threw away the generated scaffolding I played, when I started to work on the actual UI.

Grails Plug-ins
Navigating the Grails Plug-ins can be a challenge. A) you don’t want to do something that has already been done, but B) you don’t want to adopt a plugin that is not being supported or doesn’t really fit what you are trying to do. If you are looking to add an existing technology to your stack, odds are there is a plugin for it and you want to add that in via a plugin. For example, you can add jQuery to your application by adding in the javascript to your pages. However, you should be doing this via a plugin. So, for your starter application, be sure to include the process of using a plugin.

Database Schema
GORM’s create/update schema support for Hibernate works very well. While you are getting your initial application working, you should use this functionality. Only after you need to support database migration, would I worry about maintaining your database schema. Letting GORM/Hiberante manage your database for you, forces you to work with a rich object model and letting it create your schema. When I first starting writing Hibernate applications, I was very much of the school of letting your database drive your object model. Over the past 8 years, I have changed to where I prefer the object model to drive the database schema. Grails/GORM encourages that and you will find you enjoy developing more if you can focus on a rich Object Oriented design, instead of forcing in your desired database schema.

Obviously, if you are supporting an existing schema, you cannot do this. For your first Grails application, however, try to create one where you let Grails/GORM handle this for you.

Conclusion
If you are a seasoned Java/JEE Developer, it shouldn’t take you very long to learn Groovy/Grails. Give yourself a couple of weeks of being able to use it, and you will be happy you did. Now convincing your employer to use it; that is a different story.

Source