(Quick Reference)

Grailsフレームワーク - Reference Documentation

Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith

Version: 2.3.0

Translated by: T.Yamamoto, Japanese Grails Doc Translating Team. Special thanks to NTT Software.

Table of Contents

1 イントロダクション

Java web development as it stands today is dramatically more complicated than it needs to be. Most modern web frameworks in the Java space are over complicated and don't embrace the Don't Repeat Yourself (DRY) principles.
現在のJavaでのWeb開発は必要以上に複雑です。JavaのほとんどのWebフレームワークは複雑でDon't Repeat Yourself (DRY)ではありません。

Dynamic frameworks like Rails, Django and TurboGears helped pave the way to a more modern way of thinking about web applications. Grails builds on these concepts and dramatically reduces the complexity of building web applications on the Java platform. What makes it different, however, is that it does so by building on already established Java technologies like Spring and Hibernate.

Grails is a full stack framework and attempts to solve as many pieces of the web development puzzle through the core technology and its associated plugins. Included out the box are things like:

  • An easy to use Object Relational Mapping (ORM) layer built on Hibernate
  • An expressive view technology called Groovy Server Pages (GSP)
  • A controller layer built on Spring MVC
  • A command line scripting environment built on the Groovy-powered Gant
  • An embedded Tomcat container which is configured for on the fly reloading
  • Dependency injection with the inbuilt Spring container
  • Support for internationalization (i18n) built on Spring's core MessageSource concept
  • A transactional service layer built on Spring's transaction abstraction

  • Hibernate上に構築された、簡単に利用できるオブジェクト・リレーショナル・マッピング(ORM)レイヤ
  • 表現豊かなビューテクノロジーGroovy Server Pages (GSP)
  • コントローラレイヤは Spring MVCを利用
  • コマンドラインスクリプト環境にはGroovy版のAnt Gant
  • リロード可能に設定された組込 Tomcat
  • 組込 Spring による依存注入
  • SpringのMessageSourceで実装された国際化(i18n)対応
  • Springフレームワークのトランザクション概念によるサービスレイヤのトランザクション

All of these are made easy to use through the power of the Groovy language and the extensive use of Domain Specific Languages (DSLs)
これら全ては、 Groovy と多くのDomain Specific Languages (DSL ドメイン特化言語)を活用して簡単に使用できるように実装されています。

This documentation will take you through getting started with Grails and building web applications with the Grails framework.

1.1 Grails 2.3の新機能

h4. Improved Dependency Management


The default dependency resolution engine used by Grails has been changed to Aether, the dependency resolution engine used by Maven. Which engine you use can be configured in BuildConfig:
Grailsでデフォルトで使用されている依存管理エンジンが、Mavenで使用されているエンジンの Aether に変更されました。 BuildConfig で設定をすることでどちらのエンジンを使用するか変更可能です。

grails.project.dependency.resolver = "maven" // or ivy

Using Aether dependency resolution in Grails results in the same behavior as when using the Maven build tool, meaning improved snapshot handling, understanding of custom packaging types and so on.

In addition, the dependency-report command has been updated to print the dependency graph of the console, which helps in diagnosing dependency resolution failures. See the chapter on Dependency Resolution for more information.
そしてさらに、 dependency-report コマンドも改良され、依存問題の解決を手助けするために、依存関係のグラフがコンソールに表示されるようになりました。 詳しくは 依存性解決 のドキュメントを参照してください。

h4. Data Binder


Grails 2.3 includes a new data binding mechanism which is more flexible and easier to maintain than the data binder used in previous versions. The new data binder includes numerous enhancements including:
Grails 2.3では、以前のバージョンよりもフレキシブルで保守性の高く簡単な新データバインダーを実装しています。

  • フィールドごとのカスタムデータフォーマット - BindingFormat
  • ユーザ定義可能なデータコンバーター - ValueConverter
  • ユーザ定義フォーマットデータコンバーター - BindingFormat FormattedValueConverter
  • クラスごとのカスタムバインディング - BindUsing
  • フィールドごとのカスタムバインディング - BindUsing
  • デフォルトで全ての空文字列とブランクはデータバインディングでnullに変換されます(設定可能)

See the Data Binding section for details.
詳細は データバインディング のセクションを参照してください。

The legacy data binder may be used by assigning true to the grails.databinding.useSpringBinder property in grails-app/conf/Config.groovy. Note that the legacy binder does not support any of the new features provided by the new data binder.
grails-app/conf/Config.groovygrails.databinding.useSpringBinder プロパティを true にすることで以前のデータバインダーに変更することができます。 以前のバインダーは今回実装された新機能には対応していません。


If a request is made to a controller action which accepts a command object and the request includes a body, the body will be parsed and used to do data binding to the command object. This simplifies use cases where a request includes a JSON or XML body (for example) that can be bound to a command object. See the Command Objects documentation for more details.

コントローラアクションがコマンドオブジェクトを受け取れる状態でリクエストがボディを含んでいる場合、ボディの内容はパースされコマンドオブジェクトにデータバインドされます。この機能は、リクエストの内容が対象のコマンドオブジェクトに対応したJSONまたXMLのボディを含んでいる処理を単純化します。 詳細は Command Objects のドキュメントを参照してください。


When a domain class is used as a command object and there is an id request parameter, the framework will retrieve the instance of the domain class from the database using the id request parameter. See the Command Objects documentation for more details.

ドメインクラスをコマンドオブジェクトとして使用して、リクエストパラメータに id が存在した場合は、 id を使用してデータベースからドメインクラスインスタンスを取り出します。 詳細は Command Objects のドキュメントを参照してください。

h4. Forked Execution


All major commands can now be forked into a separate JVM, thus isolating the build path from the runtime / test paths. Forked execution can be controlled via the BuildConfig:
全てのメジャーなコマンドが別々のJVMへフォークされるようになり、ビルドパスをランタイム/テストから分離します。 フォーク実行のパラメータは BuildConfig に定義できます:

grails.project.fork = [
   test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true], // configure settings for the test-app JVM
   run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256], // configure settings for the run-app JVM
   war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256], // configure settings for the run-war JVM
   console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]// configure settings for the Console UI JVM
grails.project.fork = [
   test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true], // test-app用JVMへの設定
   run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256], // run-app用JVMへの設定
   war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256], // run-war用JVMへの設定
   console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]// console用JVMへの設定

See the documentation on Forked Mode for more information.
詳しくは フォークモード のドキュメントを参照してください。

h4. Test Runner Daemon


To speed up testing when using forked execution a new daemon will start-up in the background to run tests when using interactive mode. You can restart the daemon with the restart-daemon command from interactive mode:
インタラクティブモードでテストを実行する際にバックグラウンドでデーモンが起動してテストがフォーク実行されテスト効率がアップします。デーモンはインタラクティブモードで restart-daemon コマンド実行すると再起動できます。

$ grails> restart-daemon

h4. Server-Side REST Improvements


Grails' REST support has been significantly improved with the addition of the following features:

  • Rich REST URL Mapping support with supports for resource mappings, singular resource mappings, nested resources, versioning and more
  • New extensible response rendering and binding APIs
  • Support for HAL, Atom and Hypermedia (HATEAOS)
  • Scaffolding for REST controllers

  • リソースマッピング、シンギュラリソースマッピング、ネステッドリソース、バージョニングなどの、豊富なREST URLマッピングサポート
  • 新たな拡張可能なレスポンスレンダリングとバインディングAPI
  • HAL, Atom, Hypermedia (HATEAOS)対応
  • RESTコントローラのスカッフォルディング

See the user guide for more information.

h4. New Scaffolding 2.0 Plugin


Grails' Scaffolding feature has been split into a separate plugin. Version 2.0 of the plugin includes support for generating REST controllers, Async controllers, and Spock unit tests.

h4. URL Mappings May Specify A Redirect


URL Mappings may now specify that a redirect should be triggered when the mapping matches an incoming request:
class UrlMappings {
    static mappings = {
        "/viewBooks"(redirect: '/books/list')
        "/viewAuthors"(redirect: [controller: 'author', action: 'list'])
        "/viewPublishers"(redirect: [controller: 'publisher', action: 'list', permanent: true])

// … } }

See the user guide for more information.

h4. Async support


Grails 2.3 features new Asynchronous Programming APIs that allow for asynchronous processing of requests and integrate seamlessly with GORM. Example:
Grails 2.3では、リクエストの非同期処理と、GORMとシームレスに統合した新たな非同期プログラミングAPIを提供しています。 例:

import static grails.async.Promises.*
def index() {
   tasks books: Book.async.list(),
         totalBooks: Book.async.count(),
         otherValue: {
           // do hard work

See the documentation for further information.
詳しくは、 ドキュメント を参照してください。

h4. Encoding / Escaping Improvements

エンコーディング / エスケーピングの向上

Grails 2.3 features dedicated support for Cross Site Scripting (XSS) prevention, including :
Grails 2.3では専用の クロスサイトスクリプティング(XSS)防御を実装しています。

  • Defaulting to HTML escaping all GSP expressions and scriptlets
  • Context sensitive encoding switching for tags
  • Double encoding prevention
  • Optional automatic encoding of all data in a GSP page not considered safe

  • デフォルトでGSPエクスプレッションとスクリプトレットをHTMLエスケーピング
  • タグでの状況依存エンコーディング切替
  • 多重エンコーディング防止
  • GSPページ内の全てのデータに対して安全と判断しない場合の自動エンコーディング

See the documentation on Cross Site Scripting (XSS) prevention for more information.
詳しくは、 クロスサイトスクリプティング(XSS)防御 のドキュメントを参照してください。

h4. Hibernate 3 and 4 support

Hibernate 3と4をサポート

The GORM for Hibernate 3 support for Grails has been extracted into a separate project, allowing new support for Hibernate 4 as a separate plugin.
新たにHibernate 4をプラグインでサポートするために、Hibernate 3用のGORMは、本体から別のプラグインプロジェクトとなりました。

h4. Controller Exception Handling


Controllers may define exception handler methods which will automatically be invoked any time an action in that controller throws an exception.

// grails-app/controllers/demo/DemoController.groovy
package demo

class DemoController {

def someAction() { // do some work }

def handleSQLException(SQLException e) { render 'A SQLException Was Handled' }

def handleBatchUpdateException(BatchUpdateException e) { redirect controller: 'logging', action: 'batchProblem' }

def handleNumberFormatException(NumberFormatException nfe) { [problemDescription: 'A Number Was Invalid'] } }

See the controller exception handling docs for more information.
詳しくは、 ドキュメント を参照してください。

h4. Namespaced Controllers


Controllers may now be defined in a namespace which allows for multiple controllers to be defined with the same name in different packages.
// grails-app/controllers/com/app/reporting/AdminController.groovy
package com.app.reporting

class AdminController {

static namespace = 'reports'

// … }

// grails-app/controllers/com/app/security/AdminController.groovy
package com.app.security

class AdminController {

static namespace = 'users'

// … }

// grails-app/conf/UrlMappings.groovy
class UrlMappings {

static mappings = { '/userAdmin' { controller = 'admin' namespace = 'users' }

'/reportAdmin' { controller = 'admin' namespace = 'reports' }

"/$namespace/$controller/$action?"() } }

<g:link controller="admin" namespace="reports">Click For Report Admin</g:link>
<g:link controller="admin" namespace="users">Click For User Admin</g:link>

詳しくは、 ドキュメント を参照してください。

h4. Command Line


The create-app command will now by default generate the command line grailsw wrapper for newly created applications. The --skip-wrapper switch may be used to prevent the wrapper from being generated.
create-app コマンドがデフォルトでgrailswラッパーを生成するようになりました。ラッパーを生成しない場合は --skip-wrapper オプションを指定してください。

grails create-app appname --skip-wrapper

1.2 Grails 2.2の新機能

Namespace Support

Grails 2.2 includes improved support for managing naming conflicts between artifacts provided by an application and its plugins.
Grails 2.2では、アプリケーションとプラグインで提供するアーテファクト間での名前衝突を回避するための管理機能向上が含まれています。

Bean names for Service artifacts provided by a plugin are now prefixed with the plugin name. For example, if a Service named com.publishing.AuthorService is provided by a plugin named PublishingUtilities and another Service named com.bookutils.AuthorService is provided by a plugin named BookUtilities, the bean names for those services will be publishingUtilitiesAuthorService and bookUtilitiesAuthorService respectively. If a plugin provides a Service that does not have a name which conflicts with any other Service, then a bean alias will automatically be created that does not contain the prefix and the alias will refer to the bean referenced by the prefixed name. Service artifacts provided directly by the application will have no prefix added to the relevant bean name. See the dependency injection and services docs.
プラグインで提供されたサービスアーテファクトビーン名称は、プリフィックスとしてプラグイン名が使用されます。例えば、 PublishingUtilities という名称のプラグインで提供された com.publishing.AuthorService という名称のサービスと、 BookUtilities という名称のプラグインで提供された com.bookutils.AuthorService という名称のサービスが存在した場合、それぞれのビーン名称は、 publishingUtilitiesAuthorServicebookUtilitiesAuthorService になります。 もし他のサービス名称がプラグインが提供したサービスの名称に衝突しない場合は、自動的にプリフィックスの無いビーンエイリアスを生成して、プリフィックスの存在するビーンを参照します。 アプリケーションで直接提供するサービスアーティファクトには、プリフィックスは追加されません。 依存注入とサービスも参照。

Domain classes provided by a plugin will have their default database table name prefixed with the plugin name if the grails.gorm.table.prefix.enabled config property is set to true. For example, if the PublishingUtilities plugin provides a domain class named Book, the default table name for that domain class will be PUBLISHING_UTILITIES_BOOK if the grails.gorm.table.prefix.enabled config property is set to true.

プラグインで提供されたドメインクラスは、 grails.gorm.table.prefix.enabledtrue に設定されている場合、テーブル名称にプラグイン名のプリフィックスが追加されます。例として、 PublishingUtilities プラグインが提供した Book とい名称のドメインクラスであれば、テーブル名称が PUBLISHING_UTILITIES_BOOK となります。

URL Mappings may now include a plugin attribute to indicate that the controller referenced in the mapping is provided by a particular plugin.
URLマッピングには、プラグインが提供したコントローラを参照させるために、 plugin 属性を使用します。
static mappings = {

// requests to /bookAuthors will be handled by the // AuthorController provided by the BookUtilities plugin "/bookAuthors" { controller = 'author' plugin = 'bookUtilities' }

// requests to /publishingAuthors will be handled by the // AuthorController provided by the Publishing plugin "/publishingAuthors" { controller = 'author' plugin = 'publishing' } }

See the namespaced controllers docs for more information.
詳しくは コントローラネームスペース を参照してください。

Controller methods and GSP Tags which accept a controller name as a paramater now support an optional parameter indicating that the controller is provided by a specific plugin.
コントローラメソッドとGSPタグにおいても、プラグインが提供したコントローラを参照させるために、 plugin 属性を使用します。

<g:link controller="user" plugin="springSecurity">Manage Users</g:link>

class DemoController {
    def index() {
        redirect controller: 'user', action: 'list', plugin: 'springSecurity'

Forked Tomcat Execution

Grails 2.2 supports forked JVM execution of the Tomcat container in development mode. This has several benefits including:
Grails 2.2では、開発モードにおいて、Tomcatコンテナを実行するJVMのフォーク実行に対応しました。幾つかの利点は次のようになります:

  • Reduced memory consumption, since the Grails build system can exit
  • Isolation of the build classpath from the runtime classpath
  • The ability to deploy other Grails/Spring applications in parallel without conflicting dependencies

  • Grailsビルドシステムから抜けられるため、メモリーの消耗を減らします。
  • ランタイムクラスパスから、独立したビルドクラスパス。
  • 依存衝突無く並行して、別のGrails/Springアプリケーションのデプロイを可能にします。

See the documentation on using forked mode for more information.
フォークモードの使用と情報は、 ドキュメント を参照してください。

SQL Projections In Criteria Queries

Grails 2.2 adds new functionality to criteria queries to provide access to Hibernate's SQL projection API.
Grails 2.2から、クライテリアクエリーで、HibernateのSQLプロジェクションAPIにアクセスが可能になりました。

// Use SQL projections to retrieve the perimeter and area of all of the Box instances…
def c = Box.createCriteria()

def results = c.list { projections { sqlProjection '(2 * (width + height)) as perimiter, (width * height) as area', ['perimeter', 'area'], [INTEGER, INTEGER] } }

See the Criteria section for more information.
詳しくは Criteria を参照

Groovy 2

Grails 2.2 ships with Groovy 2.0, which has a bunch of new features itself.
Grails 2.2は、 多くの新機能 を提供している、Groovy 2.0を同梱しています。

1.3 Grails 2.1の新機能

Maven機能向上 / Maven マルチモジュールビルド対応
Maven Improvements / Multi Module Build Support

Grails' Maven support has been improved in a number of significant ways. Firstly it is now possible to specify plugins within your pom.xml file:
Grails Maven対応の幾つかの重要な部分が改善されました。初めに、pom.xmlファイルにプラグインを定義できるようになりました:


The Maven plugin now resolves plugins as well as jar dependencies (previously jar dependencies were resolved by Maven and plugins by Ivy). Ivy is completely disabled leaving all dependency resolution up to Maven ensuring that evictions work as expected.

There is also a new Grails create-multi-project-build script which features initial support for Maven (Gradle coming in a future release). This script can be run from a parent directory containing Grails applications and plugins and it will generate a Maven multi-module build.

Enabling Maven in a project has been made easier with the inclusion of the create-pom command:

grails create-app myapp
cd myapp
grails create-pom com.mycompany
mvn package

To create a multi-module Maven build follow these steps:

grails create-app myapp
grails create-plugin plugin-a
grails create-plugin plugin-b
grails create-multi-project-build com.mycompany:parent:1.0-SNAPSHOT
mvn install

Grails Wrapper

The Grails Wrapper allows a Grails application to build without having to install Grails and configure a GRAILS_HOME environment variable. The wrapper includes a small shell script and a couple of small bootstrap jar files that typically would be checked in to source code control along with the rest of the project. The first time the wrapper is executed it will download and configure a Grails installation. This wrapper makes it more simple to setup a development environment, configure CI and manage upgrades to future versions of Grails. When the application is upgraded to the next version of Grails, the wrapper is updated and checked in to the source code control system and the next time developers update their workspace and run the wrapper, they will automatically be using the correct version of Grails.

See the Wrapper Documentation for more details.

Debug Option

The grails command now supports a -debug option which will startup the remote debug agent. This behavior used to be provided by the grails-debug command. grails-debug is still available but is deprecated and may be removed from a future release.

grails -debug run-app

Grails Command Aliases

The alias command may be used to define aliases for grails commands.

The following command creates an alias named rit (short for "run integration tests"):

grails alias rit test-app integration:

See the alias docs for more info.

Cache Plugin

Grails 2.1 installs the cache plugin by default. This plugin provides powerful and easy to use cache functionality to applications and plugins. The main plugin provides basic map backed caching support. For more robust caching options one of the implementation plugins should be installed and configured. See the cache-redis docs and the cache-ehcache docs for details.

See the main plugin documentation for details on how to configure and use the plugin.

New GORM Methods

In Grails 2.1.1 domain classes now have static methods named first and last to retrieve the first and last instances from the datastore. See the first and last documentation for details.

1.4 Grails 2.0の新機能

This section covers the new features that are present in 2.0 and is broken down into sections covering the build system, core APIs, the web tier, persistence enhancements and improvements in testing. Note there are many more small enhancements and improvements, these sections just cover some of the highlights.

1.4.1 開発環境機能

Interactive Mode and Console Enhancements

Grails 2.0 features brand new console output that is more concise and user friendly to consume. An example of the new output when running tests can be seen below:
Grails 2.0では、より簡潔でユーザフレンドリな、新コンソール出力を実装しました。以下の例はテストを実行した内容です。

In general Grails makes its best effort to display update information on a single line and only present the information that is crucial. This means that while in previous versions of Grails the war command produced many lines of output, in Grails 2.0 only 1 line of output is produced:

In addition simply typing 'grails' at the command line activates the new interactive mode which features TAB completion, command history and keeps the JVM running to ensure commands execute much quicker than otherwise

For more information on the new features of the console refer to the section of the user guide that covers the console and interactive mode.
詳しい情報は、ユーザガイドのコンソールとインタラクティブモードを参照してください。 インタラクティブモード.

Reloading Agent

Grails 2.0 reloading mechanism no longer uses class loaders, but instead uses a JVM agent to reload changes to class files. This results in greatly improved reliability when reloading changes and also ensures that the class files stored in disk remain consistent with the class files loaded in memory, which reduces the need to run the clean command.
Grails 2.0からのリロード機能は、クラスローダを使用せずJVMエージェントを使用してクラスファイルのリロードを行います。その結果、変更保存されたクラスが確実にメモリにロードされようになり、変更時のリロードが大いに向上しました。今までより、cleanコマンドの実行回数を減らすことができます。

New Test Report and Documentation Templates

There are new templates for displaying test results that are clearer and more user friendly than the previous reports:

In addition, the Grails documentation engine has received a facelift with a new template for presenting Grails application and plugin documentation:

See the section on the documentation engine for more usage info.
詳細はドキュメントエンジンのセクションを参照してください。 プロジェクト・ドキュメント

Use a TOC for Project Docs

The old documentation engine relied on you putting section numbers into the gdoc filenames. Although convenient, this effectively made it difficult to restructure your user guide by inserting new chapters and sections. In addition, any such restructuring or renaming of section titles resulted in breaking changes to the URLs.

You can now use logical names for your gdoc files and define the structure and section titles in a YAML table-of-contents file, as described in the section on the documentation engine. The logical names appear in the URLs, so as long as you don't change those, your URLs will always remain the same no matter how much restructuring or changing of titles you do.

Grails 2.0 even provides a migrate-docs command to aid you in migrating existing gdoc user guides.

Enhanced Error Reporting and Diagnosis

Error reporting and problem diagnosis has been greatly improved with a new errors view that analyses stack traces and recursively displays problem areas in your code:

In addition stack trace filtering has been further enhanced to display only relevant trace information:

Line | Method
->>   9 | getValue     in Book.groovy
- - - - - - - - - - - - - - - - - - - - - - - - -
|     7 | getBookValue in BookService.groovy
|   886 | runTask . .  in ThreadPoolExecutor.java
|   908 | run          in     ''
^   662 | run . . . .  in Thread.java

H2 Database and Console

Grails 2.0 now uses the H2 database instead of HSQLDB, and enables the H2 database console in development mode (at the URI /dbconsole) so that the in-memory database can be easily queried from the browser:
Grails 2.0では、今までのHSQLDBに代わりH2データベースを使用します。H2データベース付属のコンソール機能を開発モードで有効にしています。(URI /dbconsoleで表示可能) メモリ動作のデータベースでも簡単にブラウザからクエリ実行することができます:

Plugin Usage Tracking

To enhance community awareness of the most popular plugins an opt-in plugin usage tracking system has been included where users can participate in providing feedback to the plugin community on which plugins are most popular.

This will help drive the roadmap and increase support of key plugins while reducing the need to support older or less popular plugins thus helping plugin development teams focus their efforts.

Dependency Resolution Improvements

There are numerous improvements to dependency resolution handling via Ivy including:

  • Grails now makes a best effort to cache the previous resolve and avoid resolving again unless you change BuildConfig.groovy.
  • Plugins dependencies now appear in the dependency report generated by grails dependency-report
  • Plugins published with the release plugin now publish their transitive plugin dependencies in the generated POM which are later resolved.
  • It is now possible to customize the ivy cache directory via BuildConfig.groovy

  • Grailsは、 BuildConfig.groovy を変更しない限り前回の依存解決した内容を再解決させないように前回の内容をキャッシュするようになりました。
  • プラグイン依存関係も grails dependency-report のレポートに現れるようになりました。
  • release-plugin で発行されたプラグインは、推移的なプラグイン依存をPOMに発行するようになりました。
  • ivyキャッシュ用ディレクトリを BuildConfig.groovy で変更できます。

grails.project.dependency.resolution = {
    cacheDir "target/ivy-cache"

* You can change the ivy cache directory for all projects via settings.groovy
  • settings.groovyに設定することで、全てのプロジェクトのivyキャッシュディレクトリを変更できます。

grails.dependency.cache.dir = "${userHome}/.ivy2/cache"

* It is now possible to completely disable resolution from inherited repositories (repositories defined by other plugins):
  • リポジトリの引継を完全に無効にできます(他のプラグインで定義されている場合等):

grails.project.dependency.resolution = {

repositories { inherits false // Whether to inherit repository definitions from plugins … } … }

* It is now possible to easily disable checksum validation errors:
  • チェックサムを無効にできます:

grails.project.dependency.resolution = {
    checksums false // whether to verify checksums or not

1.4.2 コア機能

Binary Plugins

Grails plugins can now be packaged as JAR files and published to standard maven repositories. This even works for GSP and static resources (with resources plugin 1.0.1). See the section on Binary plugins for more information.
Grailsプラグインは、JARファイルとしてパッケージして、Mavenリポジトリへ発行できるようになりました。GSPや静的リソースでも可能です。詳しくは、 バイナリプラグイン のセクションを参考にしてください。

Groovy 1.8
Groovy 1.8

Grails 2.0 comes with Groovy 1.8 which includes many new features and enhancements
Grails 2.0は、多くの新機能と向上をしたGroovy 1.8がバンドルされています。 Groovy 1.8 リリースノート

Spring 3.1 プロファイルサポート
Spring 3.1 Profile Support

Grails' existing environment support has been bridged into the Spring 3.1 profile support. For example when running with a custom Grails environment called "production", a Spring profile of "production" is activated so that you can use Spring's bean configuration APIs to configure beans for a specific profile.
Grailsの環境サポートがSpring 3.1プロフィールサポートとブリッジできます。例えば、Grailsの環境で"production"で動作している場合、Springプロフィール"production"がアクティベートされます。これによって、Springビーン定義APIでのビーン定義でプロフィールを指定できます。

1.4.3 Web機能

Controller Actions as Methods

It is now possible to define controller actions as methods instead of using closures as in previous versions of Grails. In fact this is now the preferred way of expressing an action. For example:

// action as a method // action as a closure
// メソッドのアクション (action as a method)
def index() {

} // クロージャのアクション (action as a closure) def index = {


Binding Primitive Method Action Arguments

It is now possible to bind form parameters to action arguments where the name of the form element matches the argument name. For example given the following form:
フォームエレメントのname属性を、アクションメソッドの引数に指定する方法でのバインドが可能になりました。 次のようなフォームを例に:

<g:form name="myForm" action="save">
    <input name="name" />
    <input name="age" />

You can define an action that declares arguments for each input and automatically converts the parameters to the appropriate type:

def save(String name, int age) {
    // remaining

Static Resource Abstraction

A new static resource abstraction is included that allows declarative handling of JavaScript, CSS and image resources including automatic ordering, compression, caching and gzip handling.
JavaScript、CSS、画像などのリソースを管理、圧縮、キャッシュ、gzipを行う 静的リソース抽象化機能 が追加されました。

Servlet 3.0 Async Features

Grails now supports Servlet 3.0 including the Asynchronous programming model defined by the specification:

def index() {
    def ctx = startAsync()
    ctx.start {
        new Book(title:"The Stand").save()
        render template:"books", model:[books:Book.list()]

Link Generation API

A general purpose LinkGenerator class is now available that is usable anywhere within a Grails application and not just within the context of a controller. For example if you need to generate links in a service or an asynchronous background job outside the scope of a request:
全面的に使用可能なリンク生成API LinkGenerator クラスが追加されました。コントローラのコンテキスト以外のどこからでも使用できます。例としてサービス、バックグラウンド処理、非同期タスク、リクエスト以外の場所でリンクが生成できます。

LinkGenerator grailsLinkGenerator

def generateLink() { grailsLinkGenerator.link(controller:"book", action:"list") }

Page Rendering API

Like the LinkGenerator the new PageRenderer can be used to render GSP pages outside the scope of a web request, such as in a scheduled job or web service. The PageRenderer class features a very similar API to the render method found within controllers:
LinkGenerator と同じく新規に追加されたAPI、 PageRenderer は、Webリクエスト以外の場所で、GSPページが描写可能です。例えば、Webサービス、スケジュールジョブなどで使用します。 PageRenderer サービスはコントローラの render メソッドと同じように使用します。

grails.gsp.PageRenderer groovyPageRenderer

void welcomeUser(User user) { def contents = groovyPageRenderer.render(view:"/emails/welcomeLetter", model:[user: user]) sendEmail { to user.email body contents } }

The PageRenderer service also allows you to pre-process GSPs into HTML templates:
PageRenderer sサービスはGSPからHTMLを生成するのも可能です。

new File("/path/to/welcome.html").withWriter { w ->
    groovyPageRenderer.renderTo(view:"/page/content", w)

Filter Exclusions

Filters may now express controller, action and uri exclusions to offer more options for expressing to which requests a particular filter should be applied.

filter1(actionExclude: 'log*') {
    before = {
        // …
filter2(controllerExclude: 'auth') {
    before = {
        // …

filter3(uriExclude: '/secure*') { before = { // … } }

Performance Improvements

Performance of GSP page rendering has once again been improved by optimizing the GSP compiler to inline method calls where possible.

HTML5 Scaffolding

There is a new HTML5-based scaffolding UI:

jQuery by Default

The jQuery plugin is now the default JavaScript library installed into a Grails application. For backwards compatibility a Prototype plugin is available. Refer to the documentation on the Prototype plugin for installation instructions.
jQueryプラグインがデフォルトのJavaScriptライブラリとしてGrailsアプリケーションにインストールされます。 下位互換として、Prototypeはプラグインとして提供しています。 Prototypeついてはプラグインのドキュメントを参考にしてください。 Prototype plugin

Easy Date Parsing

A new date method has been added to the params object to allow easy, null-safe parsing of dates:
def val = params.date('myDate', 'dd-MM-yyyy')

// or a list for formats def val = params.date('myDate', ['yyyy-MM-dd', 'yyyyMMdd', 'yyMMdd'])

// or the format read from messages.properties via the key 'date.myDate.format' def val = params.date('myDate')


The default URL Mapping mechanism supports camel case names in the URLs. The default URL for accessing an action named addNumbers in a controller named MathHelperController would be something like /mathHelper/addNumbers. Grails allows for the customization of this pattern and provides an implementation which replaces the camel case convention with a hyphenated convention that would support URLs like /math-helper/add-numbers. To enable hyphenated URLs assign a value of "hyphenated" to the grails.web.url.converter property in grails-app/conf/Config.groovy.

// grails-app/conf/Config.groovy

grails.web.url.converter = 'hyphenated'

Arbitrary strategies may be plugged in by providing a class which implements the UrlConverter interface and adding an instance of that class to the Spring application context with the bean name of grails.web.UrlConverter.BEAN_NAME. If Grails finds a bean in the context with that name, it will be used as the default converter and there is no need to assign a value to the grails.web.url.converter config property.

// src/groovy/com/myapplication/MyUrlConverterImpl.groovy

package com.myapplication

class MyUrlConverterImpl implements grails.web.UrlConverter {

String toUrlElement(String propertyOrClassName) { // return some representation of a property or class name that should be used in URLs… } }

// grails-app/conf/spring/resources.groovy

beans = { "${grails.web.UrlConverter.BEAN_NAME}"(com.myapplication.MyUrlConverterImpl) }

Web Flow input and output

It is now possible to provide input arguments when calling a subflow. Flows can also return output values that can be used in a calling flow.

1.4.4 永続化機能


The GORM API has been formalized into a set of classes (GormStaticApi, GormInstanceApi and GormValidationApi) that get statically wired into every domain class at the byte code level. The result is better code completion for IDEs, better integration with Java and the potential for more GORM implementations for other types of data stores.
GORM APIは、 GormStaticApiGormInstanceApiGormValidationApi というクラスに置き換えられたことによって、全てのドメインのバイトコードレベルに注入されます。この実装でIDEでのコード補完、Javaとの統合、様々なデータストアへのGORM実装への可能性が向上しました。

Detached Criteria and Where Queries

Grails 2.0 features support for DetachedCriteria which are criteria queries that are not associated with any session or connection and thus can be more easily reused and composed:

def criteria = new DetachedCriteria(Person).build {
    eq 'lastName', 'Simpson'
def results = criteria.list(max:4, sort:"firstName")

To support the addition of DetachedCriteria queries and encourage their use a new where method and DSL has been introduced to greatly reduce the complexity of criteria queries:

def query = Person.where {
    (lastName != "Simpson" && firstName != "Fred") || (firstName == "Bart" && age > 9)
def results = query.list(sort:"firstName")

See the documentation on DetachedCriteria and Where Queries for more information.

New findOrCreate and findOrSave Methods

Domain classes have support for the findOrCreateWhere, findOrSaveWhere, findOrCreateBy and findOrSaveBy query methods which behave just like findWhere and findBy methods except that they should never return null. If a matching instance cannot be found in the database then a new instance is created, populated with values represented in the query parameters and returned. In the case of findOrSaveWhere and findOrSaveBy, the instance is saved before being returned.
ドメインクラスに、findWhereやfindByメソッドに似た、nullを返さない、findOrCreateWhere, findOrSaveWhere, findOrCreateBy, findOrSaveByのクエリーをサポートしました。実行結果にインスタンスが見つからない場合は、指定された値で、新規にインスタンスを作成して返します。findOrSaveWhereとfindOrSaveByの場合はインスタンスを保存してからインスタンスを返します。

def book = Book.findOrCreateWhere(author: 'Douglas Adams', title: "The Hitchiker's Guide To The Galaxy")
def book = Book.findOrSaveWhere(author: 'Daniel Suarez', title: 'Daemon')
def book = Book.findOrCreateByAuthorAndTitle('Daniel Suarez', 'Daemon')
def book = Book.findOrSaveByAuthorAndTitle('Daniel Suarez', 'Daemon')

Abstract Inheritance

GORM now supports abstract inheritance trees which means you can define queries and associations linking to abstract classes:

abstract class Media {
    String title
class Book extends Media {
class Album extends Media {

} class Account { static hasMany = [purchasedMedia:Media] }


def allMedia = Media.list()

Multiple Data Sources Support

It is now possible to define multiple datasources in DataSource.groovy and declare one or more datasources a particular domain uses by default:

class ZipCode {

String code

static mapping = { datasource 'ZIP_CODES' } }

If multiple datasources are specified for a domain then you can use the name of a particular datasource as a namespace in front of any regular GORM method:

def zipCode = ZipCode.auditing.get(42)

For more information see the section on Multiple Data Sources in the user guide.
詳しくは 複数データソース を参照してください。

Database Migrations

A new database migration plugin has been designed and built for Grails 2.0 allowing you to apply migrations to your database, rollback changes and diff your domain model with the current state of the database.
データベースマイグレーションを行うプラグインが、Grails 2.0用にデザイン構築されました。現行の状況との違いや、変更のロールバックがデータベースマイグレーションで可能になります。 database migration plugin

Database Reverse Engineering

A new database reverse engineering plugin has been designed and built for Grails 2.0 that allows you to generate a domain model from an existing database schema.
データベースリバースエンジニアリングを行うプラグインが、Grails 2.0用にデザイン構築されました。既存のデータベーススキーマからドメインクラスを生成可能とします。 database reverse engineering

Hibernate 3.6
Hibernate 3.6

Grails 2.0 is now built on Hibernate 3.6
Grails 2.0では、Hibernate 3.6を使用しています。

Bag Collections

You can now use Hibernate Bags for mapped collections to avoid the memory and performance issues of loading large collections to enforce Set uniqueness or List order.
SetのユニークまたはListの順序必要としない場合でにおいて、大きなコレクションロードのメモリーとパフォーマンス問題を回避できるコレクションマッピング、Hibernate Bagが使用できるようになりました。

For more information see the section on Sets, Lists and Maps in the user guide.
詳しくは セット、リスト、マップ を参照してください。

1.4.5 テスト機能

New Unit Testing Console Output

Test output from the test-app command has been improved:

New Unit Testing API

There is a new unit testing API based on mixins that supports JUnit 3, 4 and Spock style tests (with Spock 0.6 and above). Example:
JUnit3,4,Spock(Spock 0.6以上)のテストに対応した、Mixinsベースの新しユニットテストAPIが追加されました:

import grails.test.mixin.TestFor

@TestFor(SimpleController) class SimpleControllerTests { void testIndex() { controller.home()

assert view == "/simple/homePage" assert model.title == "Hello World" } }

The documentation on testing has also been re-written around this new framework.
テストのドキュメントが、この新しいフレームワークのために書き直されました。詳細は テストのドキュメント を参照してください。

Unit Testing GORM

A new in-memory GORM implementation is present that supports many more features of the GORM API making unit testing of criteria queries, named queries and other previously unsupported methods possible.
メモリ上で動作するGORM実装により、今までにサポートされていなかった、クライテリアクエリ、名前付きクエリなど、様々なGORM APIのテストがユニットテストで可能になりました。

Faster Unit Testing with Interactive Mode

The new interactive mode (activated by typing 'grails') greatly improves the execution time of running unit and integration tests.

Unit Test スカッフォルド
Unit Test Scaffolding

A unit test is now generated for scaffolded controllers

2 スタートガイド

2.1 インストール必要条件

Before installing Grails you will need as a minimum a Java Development Kit (JDK) installed version 1.6 or above. Download the appropriate JDK for your operating system, run the installer, and then set up an environment variable called JAVA_HOME pointing to the location of this installation. If you're unsure how to do this, we recommend the video installation guides from grailsexample.net:
Grailsをインストールする前に、Java Development Kit (JDK) 1.6以上がインストール済みで、JAVA_HOMEが指定されている必要があります。一部のプラットフォームでは(OS Xの例で言うと)、自動的にJavaのインストール先を認識します。手動で定義する場合等、必要に応じて次のようにJavaの設定を行ってください。方法がわからない場合は、コチラの動画も参考にしてください。grailsexample.net

These will show you how to install Grails too, not just the JDK.

A JDK is required in your Grails development environment. A JRE is not sufficient.

On some platforms (for example OS X) the Java installation is automatically detected. However in many cases you will want to manually configure the location of Java. For example:

export JAVA_HOME=/Library/Java/Home
export PATH="$PATH:$JAVA_HOME/bin"

if you're using bash or another variant of the Bourne Shell.
Bashやその他のBourne Shellでの例です。

2.2 ダウンロードとインストール

The first step to getting up and running with Grails is to install the distribution. To do so follow these steps:

  • Download a binary distribution of Grails and extract the resulting zip file to a location of your choice
  • Set the GRAILS_HOME environment variable to the location where you extracted the zip
    • On Unix/Linux based systems this is typically a matter of adding something like the following export GRAILS_HOME=/path/to/grails to your profile
    • On Windows this is typically a matter of setting an environment variable under My Computer/Advanced/Environment Variables
  • Then add the bin directory to your PATH variable:
    • On Unix/Linux based systems this can be done by adding export PATH="$PATH:$GRAILS_HOME/bin" to your profile
    • On Windows this is done by modifying the Path environment variable under My Computer/Advanced/Environment Variables

  • Grailsをダウンロードし、任意の場所にzipファイルを解凍します。
  • zipファイルを解凍した場所にGRAILS_HOME環境変数を設定します。
    • Unix/Linuxベースのシステムでは、次のようなものをプロファイル(.profileなど)に追加します。export GRAILS_HOME=/path/to/grails
    • Windowsでは、マイコンピュータ>詳細>環境変数に設定します。
  • さらに、PATH変数にbinディレクトリを追加する必要があります。
    • Unix/Linuxベースのシステムでは、このように設定します。export PATH="$PATH:$GRAILS_HOME/bin"
    • Windowsでは、マイコンピュータ>詳細>環境変数のPathに%GRAILS_HOME%binを追加します。

If Grails is working correctly you should now be able to type grails -version in the terminal window and see output similar to this:

Grails version: 2.0.0

2.3 アプリケーション作成

To create a Grails application you first need to familiarize yourself with the usage of the grails command which is used in the following manner:

grails command name
grails [コマンド名]

Run create-app to create an application:

grails create-app helloworld

This will create a new directory inside the current one that contains the project. Navigate to this directory in your console:

cd helloworld

2.4 Hello Worldの例

Let's now take the new project and turn it into the classic "Hello world!" example. First, change into the "helloworld" directory you just created and start the Grails interactive console:
それではさっそく、この新たなプロジェクトで、おなじみの「Hello World!」を構築していきましょう。 はじめに、作成したhelloworldディレクトリへ移動し、Grailsのインタラクティブコンソールを起動します:

$ cd helloworld
$ grails

You should see a prompt that looks like this:

What we want is a simple page that just prints the message "Hello World!" to the browser. In Grails, whenever you want a new page you just create a new controller action for it. Since we don't yet have a controller, let's create one now with the create-controller command:
はじめに作るのはブラウザへ「Hello World!」というメッセージを表示するシンプルなページです。 Grailsで新しいページが必要な場合は、新たにコントローラのアクションを作成します。 まだコントローラが存在しない場合は、create-controllerコマンドで新たに作成しましょう:

grails> create-controller hello

Don't forget that in the interactive console, we have auto-completion on command names. So you can type "cre" and then press <tab> to get a list of all create-* commands. Type a few more letters of the command name and then <tab> again to finish.
インタラクティブコンソールではコマンド名の自動補完が効きます。 そのためcreと入力し、そしてすべてのcreate-*コマンド一覧を表示するために<tab>を押します。 さらにいくつかのコマンド名を入力し、そして補完を完了するために<tab>をもう1度押します。

The above command will create a new controller in the grails-app/controllers/helloworld directory called HelloController.groovy. Why the extra helloworld directory? Because in Java land, it's strongly recommended that all classes are placed into packages, so Grails defaults to the application name if you don't provide one. The reference page for create-controller provides more detail on this.
上記のコマンドはgrails-app/controllers/helloworldディレクトリにHelloController.groovyという名前で新たなコントローラを作成します。 なぜhelloworldディレクトリに作成されるのでしょうか? これはJavaの世界では、すべてのクラスはパッケージに所属することが推奨されているためです。 もしパッケージが明示的に指定されなかった場合、Grailsはパッケージ名のデフォルトにアプリケーション名を使用します。 create-controllerのリファレンスページではより詳細な情報を提供しています。

We now have a controller so let's add an action to generate the "Hello World!" page. The code looks like this:
さてコントローラが作成できたので、「Hello World!」ページを生成するアクションを追加しましょう。 次のようなコードになります:

package helloworld

class HelloController {

def index() { render "Hello World!" } }

The action is simply a method. In this particular case, it calls a special method provided by Grails to render the page.
このアクションはシンプルなメソッドになっています。 ここでは、Grailsによって提供されているページを表示するrenderメソッドを呼んでいます。

Job done. To see your application in action, you just need to start up a server with another command called run-app:
これで準備は完了です。 アプリケーションの動作を確認するには、run-appと呼ばれる他のコマンドを使いサーバを起動する必要があります:

grails> run-app

This will start an embedded server on port 8080 that hosts your application. You should now be able to access your application at the URL http://localhost:8080/helloworld/ - try it!
これはアプリケーションが動作する組み込みサーバを8080ポートで起動します。 これによりhttp://localhost:8080/helloworld/というURLからアプリケーションにアクセス可能になっています。さっそくアクセスしてみましょう!

If you see the error "Server failed to start for port 8080: Address already in use", then it means another server is running on that port. You can easily work around this by running your server on a different port using -Dserver.port=9090 run-app. '9090' is just an example: you can pretty much choose anything within the range 1024 to 49151.
もし「Server failed to start for port 8080: Address already in use」というエラーが表示された場合は、他のサーバがそのポートで起動していることを意味します。 これは-Dserver.port=9090 run-appのように異なるポートを使ってサーバを起動することで簡単に回避できます。 この9090は単なる例で、1024から49151の間で任意のポートを指定できます。

The result will look something like this:

This is the Grails intro page which is rendered by the grails-app/view/index.gsp file. It detects the presence of your controllers and provides links to them. You can click on the "HelloController" link to see our custom page containing the text "Hello World!". Voila! You have your first working Grails application.
これはgrails-app/view/index.gspファイルによって表示されるGrailsのイントロページです。 このページ内に作成したコントローラが表示され、そのコントローラへのリンクが提供されていることに気が付いたでしょうか? 「Hello World!」というテキストを含むカスタムページを表示するために、「HelloController」リンクをクリックします。 じゃじゃーん!これで初めてのGrailsアプリケーションが完成です。

One final thing: a controller can contain many actions, each of which corresponds to a different page (ignoring AJAX at this point). Each page is accessible via a unique URL that is composed from the controller name and the action name: /<appname>/<controller>/<action>. This means you can access the Hello World page via /helloworld/hello/index, where 'hello' is the controller name (remove the 'Controller' suffix from the class name and lower-case the first letter) and 'index' is the action name. But you can also access the page via the same URL without the action name: this is because 'index' is the default action . See the end of the controllers and actions section of the user guide to find out more on default actions.
最後にもうひとつ。 コントローラは異なるページ(ここではAJAXは置いといて)を表示する複数のアクションを含むことができます。 これらのページは、それぞれ固有のURLを通じてアクセスできます。このURLは/<appname>/<controller>/<action>の形式でコントローラ名、アクション名から構成されます。 /helloworld/hello/indexを通してHello Worldページにアクセスできますが、これはhelloがコントローラ名(クラス名からサフィックスのControllerを削除して、最初の文字を小文字する)、indexがアクション名になります。 ですが、ここではアクション名を削除したURLでも同じページにアクセスできます。これはindexデフォルトアクション であるためです。 このデフォルトアクションの詳細はユーザガイドのコントローラとアクションセクションの最後を参照してください。

2.5 インタラクティブモードの利用

Grails 2.0 features an interactive mode which makes command execution faster since the JVM doesn't have to be restarted for each command. To use interactive mode simple type 'grails' from the root of any projects and use TAB completion to get a list of available commands. See the screenshot below for an example:
Grails 2.0では、コマンドの起動を速くするために、コマンド毎にJVMに再起動が必要無いインタラクティブモードを提供しています。インタラクティブモードを使用するには、プロジェクトルートで単に'grails'と入力するだけです。使用可能なコマンドをタブ補完することもできます。例としてスクリーンショットを参照してください:

For more information on the capabilities of interactive mode refer to the section on Interactive Mode in the user guide.

2.6 IDEの設定

IntelliJ IDEA

IntelliJ IDEA and the JetGroovy plugin offer good support for Groovy and Grails developers. Refer to the section on Groovy and Grails support on the JetBrains website for a feature overview.
IntelliJ IDEAJetGroovyプラグインは、Groovy&Grailsの開発者に十分な機能を提供します。機能概要については、JetBrainsのウェブサイトのGroovy and Grailsを参照してください。

IntelliJ IDEA comes in two flavours; the open source "Community Edition" and the commercial "Ultimate Edition".
IntelliJ IDEAには、オープンソース版の"Community Edition"と商用版の"Ultimate Edition"という2種類のバージョンが存在します
Both offers support for Groovy, but only Ultimate Edition offers Grails support.
両方Groovyをサポートしていますが、Grailsは、"Ultimate Edition"のみの対応となります。

With Ultimate Edition, there is no need to use the grails integrate-with --intellij command, as Ultimate Edition understands Grails projects natively. Just open the project with File -> New Project -> Create project from existing sources.
Ultimate Editionでは、 grails integrate-with --intellij コマンドを実行する必要がありません。Ultimate Editionでは、Grailsにネイティブ対応しています。プロジェクトを File -> New Project -> Create project で開くだけで良いです。

You can still use Community Edition for Grails development, but you will miss out on all the Grails specific features like automatic classpath management, GSP editor and quick access to Grails commands.
Community EditionでもGrails開発に使用できますが、Grails向けの機能や自動クラスパス管理、GSPエディタ、Grailsコマンドへの対応が存在しません。

To integrate Grails with Community Edition run the following command to generate appropriate project files:
GrailsでCommunity Editionの設定をするには、次のコマンドを実行してプロジェクトファイルを生成します。

grails integrate-with --intellij


We recommend that users of Eclipse looking to develop Grails application take a look at Groovy/Grails Tool Suite, which offers built in support for Grails including automatic classpath management, a GSP editor and quick access to Grails commands. See the STS Integration page for an overview.
Eclipse ユーザーがGrailsアプリケーションの開発をする際は、Groovy/Grails Tool Suiteを探して取得することをお勧めします。それは自動クラスパス管理機能、GSPエディタやGrailsコマンドへの迅速なアクセス機能を含んだGrailsのためのサポートが組み込まれて提供されています。概要については、STS Integrationのページを参照してください。


NetBeans provides a Groovy/Grails plugin that automatically recognizes Grails projects and provides the ability to run Grails applications in the IDE, code completion and integration with the Glassfish server. For an overview of features see the NetBeans Integration guide on the Grails website which was written by the NetBeans team.
他にも良好なオープンソースのIDEとしてSunのNetBeansがあります。NetBeansはGroovy/Grailsプラグインで自動的にGrailsプロジェクトを認識します。また、IDEでのGrailsアプリケーションの実行、コード補完、SunのGlassfishサーバとの連携などの機能も提供しています。機能概要については、NetBeansチームによって記述されたGrails公式サイト上のNetBeans Integrationガイドを参照してください。


Since Grails' focus is on simplicity it is often possible to utilize more simple editors and TextMate on the Mac has an excellent Groovy/Grails bundle available from the TextMate bundles SVN.
単純さに焦点があたっているGrailsは、より単純なエディタを利用することが可能です。そしてMac上の TextMateTextmateにバンドルされたSVNから優秀なGroovy/Grailsバンドルを利用可能です。

To integrate Grails with TextMate run the following command to generate appropriate project files:

grails integrate-with --textmate

Alternatively TextMate can easily open any project with its command line integration by issuing the following command from the root of your project:

mate .

2.7 Convention over Configuration 設定より規約

Grails uses "convention over configuration" to configure itself. This typically means that the name and location of files is used instead of explicit configuration, hence you need to familiarize yourself with the directory structure provided by Grails.
Grailsは、"convention over configuration"を使用して、自動的に設定をおこないます。一般的に、名前とファイルの位置が明確な構成の代わりに使われることを意味します。それゆえに、Grailsによって提供されるディレクトリ構造に慣れ親む必要があります。

Here is a breakdown and links to the relevant sections:

2.8 アプリケーションの起動

Grails applications can be run with the built in Tomcat server using the run-app command which will load a server on port 8080 by default:

grails run-app

You can specify a different port by using the server.port argument:

grails -Dserver.port=8090 run-app

Note that it is better to start up the application in interactive mode since a container restart is much quicker:

$ grails
grails> run-app
| Server running. Browse to http://localhost:8080/helloworld
| Application loaded in interactive mode. Type 'stop-app' to shutdown.
| Downloading: plugins-list.xml
grails> stop-app
| Stopping Grails server
grails> run-app
| Server running. Browse to http://localhost:8080/helloworld
| Application loaded in interactive mode. Type 'stop-app' to shutdown.
| Downloading: plugins-list.xml

More information on the run-app command can be found in the reference guide.

2.9 アプリケーションのテスト

The create-* commands in Grails automatically create unit or integration tests for you within the test/unit or test/integration directory. It is of course up to you to populate these tests with valid test logic, information on which can be found in the section on Testing.

To execute tests you run the test-app command as follows:

grails test-app

2.10 アプリケーションのデプロイ

Grails applications are deployed as Web Application Archives (WAR files), and Grails includes the war command for performing this task:

grails war

This will produce a WAR file under the target directory which can then be deployed as per your container's instructions.

Unlike most scripts which default to the development environment unless overridden, the war command runs in the production environment by default. You can override this like any script by specifying the environment name, for example:

grails dev war

NEVER deploy Grails using the run-app command as this command sets Grails up for auto-reloading at runtime which has a severe performance and scalability implications

When deploying Grails you should always run your containers JVM with the -server option and with sufficient memory allocation. A good set of VM flags would be:

-server -Xmx512M -XX:MaxPermSize=256m

2.11 サポートされている Java EE コンテナ

Grails runs on any container that supports Servlet 2.5 and above and is known to work on the following specific container products:
GrailsはServlet 2.5をサポートする任意のWebコンテナで動作します。次の製品で動作することが確認されています。
  • Tomcat 7
  • Tomcat 6
  • SpringSource tc Server
  • Eclipse Virgo
  • GlassFish 3
  • GlassFish 2
  • Resin 4
  • Resin 3
  • JBoss 6
  • JBoss 5
  • Jetty 8
  • Jetty 7
  • Jetty 6
  • IBM Websphere 7.0
  • IBM Websphere 6.1
  • Oracle Weblogic 10.3
  • Oracle Weblogic 10
  • Oracle Weblogic 9
  • IBM WebSphere 8.5
  • IBM WebSphere 8.0
  • IBM WebSphere 7.0
  • IBM WebSphere 6.1

It's required to set "-Xverify:none" in "Application servers > server > Process Definition > Java Virtual Machine > Generic JVM arguments" for older versions of WebSphere. This is no longer needed for WebSphere version 8 or newer.
古いバージョンのWebSphereでは、"Application servers > server > Process Definition > Java Virtual Machine > Generic JVM arguments"に、"-Xverify:none"を設定する必要があります。WebSphere 8 以降では不要です。
Some containers have bugs however, which in most cases can be worked around. A list of known deployment issues can be found on the Grails wiki.

2.12 アプリケーション生成

To get started quickly with Grails it is often useful to use a feature called Scaffolding to generate the skeleton of an application. To do this use one of the generate-* commands such as generate-all, which will generate a controller (and its unit test) and the associated views:

grails generate-all Book

2.13 アーテファクトの作成

Grails ships with a few convenience targets such as create-controller, create-domain-class and so on that will create Controllers and different artefact types for you.
These are just for your convenience and you can just as easily use an IDE or your favourite text editor.
For example to create the basis of an application you typically need a domain model:

grails create-domain-class book

This will result in the creation of a domain class at grails-app/domain/Book.groovy such as:

class Book {

There are many such create-* commands that can be explored in the command line reference guide.

To decrease the amount of time it takes to run Grails scripts, use the interactive mode.

3 Grails下位バージョンからの更新

A number of changes need to considered when upgrading your application from Grails 2.2, including:
Grails 2.2 から更新する際にいくつか考慮する点があります。

h4. New Data Binder


There is a new data binding mechanism written from the ground up to meet Grails' needs. If you wish to continue using Spring for data binding then you must set the grails.databinding.useSpringBinder property to true in grails-app/conf/Config.groovy

h4. Dependency Resolution changes


Although dependency resolution using Ivy is still supported, the default for Grails 2.3 is to use Aether and the Ivy support will not be improved upon going forward. You may wish to consider using Aether instead for your existing applications by setting the following in grails-app/conf/BuildConfig.groovy:

grails.project.dependency.resolver = "maven" // or ivy

Dependency Metadata Changes

In addition, the POM and dependency metadata for Grails 2.3 has been re-arranged and cleaned up so that only direct dependencies are specified for an application and all other dependencies are inherited transitvely. This has implications to the upgrade since, for example, Ehcache is now a transitive dependency of the Hibernate plugin, whilst before it was a direct dependency. If get a compilation error related to Ehcache, it is most likely that you don't have the Hibernate plugin installed and need to directly declare the Ehcache dependency:

compile "net.sf.ehcache:ehcache-core:2.4.6"

In addition, excludes may no longer work and may need adjusting when upgrading due to how the metadata has changed. Run the dependency-report to see the new dependency metadata and make adjustments accordingly.

A common error that may occur when upgrading is:

| Configuring classpath
:: problems summary ::
    ::          UNRESOLVED DEPENDENCIES         ::
    :: org.springframework#spring-test;3.2.2.RELEASE: configuration 
    not found in org.springframework#spring-test;3.2.2.RELEASE: 'compile'. 
    It was required from org.grails#grails-plugin-testing;2.3.0.BUILD-SNAPSHOT compile

This is caused by a plugin that depends on an old version of spring-test (for example the Mail plugin). To correct this run grails dependency-report and search for plugins that have a transitive dependency on spring-test and exclude them. For example:

plugins {
  compile ':mail:1.0', {
    excludes 'spring-test'

However, longer term to solve problems like this we recommend that users move away from Ivy and use Aether instead for dependency resolution:


h4. No initial offline mode with Aether


Aether does not support resolving dependencies from a flat file system. This means that the jars we ship with Grails in GRAILS_HOME/lib are not used for the first resolve, but instead the jars are obtained from Maven central. After they have been obtained from Maven central then Aether operates fine offline.

If however you do not have the necessary jars in your local Maven repository, then the only way to get offline execution is to enable Ivy via BuildConfig (see above).

Scaffolding moved to a plugin and rewritten

If you have dynamically scaffolded controllers in your application then you will need to configure the 1.0 version of the Scaffolding plugin in BuildConfig:

plugins {
  compile ':scaffolding:1.0.0'

By default for new applications the 2.0 version of the scaffolding plugin is used, which is not backwards compatible with 1.0.

h4. Forked Execution for Testing


Tests are now by default executed in a forked JVM (although this can be disabled). One implication of this is that tests will be slower to execute when using:

grails test-app

The reason for this is the need to load a separate JVM to execute tests. To mitigate this Grails interactive mode has been updated to load a background JVM that can be resumed. If you do:

$ grails // load interactive mode
$ grails -> test-app
$ grails -> test-app

Test execution will be noticably faster and is the recommended way to run tests in Grails. On older hardware that does not include multiple cores (to run the separate JVMs) it is recommended you disable forked execution for tests to achieve faster test execution times:

forkConfig = [maxMemory: 1024, minMemory: 64, debug: false, maxPerm: 256]
grails.project.fork = [
   test: false, // disable forked execution for test-app
   run: forkConfig, // configure settings for the run-app JVM

h4. Forked Execution and the Reloading Agent


In Grails 2.3 the reloading agent is no longer on the build system path unless you pass the -reloading flag to the grails command:

grails -reloading run-app

The reason for this is that the default in Grails 2.3 and above is to load Grails application in a forked JVM and enable the agent for the forked JVM. If you do not wish to use forked JVMs then you must ensure that you run Grails with the -reloading flag. Alternatively, you can enable forking with the following configuration in BuildConfig:

forkConfig = [maxMemory: 1024, minMemory: 64, debug: false, maxPerm: 256]
grails.project.fork = [
   test: forkConfig, // configure settings for the test-app JVM
   run: forkConfig, // configure settings for the run-app JVM
   war: forkConfig, // configure settings for the run-war JVM
   console: forkConfig // configure settings for the Swing console JVM

h4. Forked Execution and Remote Debugging


The grails-debug command will no longer work with Grails for remote debugging sessions. The reason is the command enabled debugging for the build system JVM, but not the JVM used in forked execution. The solution to this is to use the debug-fork command line argument:

grails --debug-fork run-app

Alternatively you can set the debug setting to true in BuildConfig and use the regular grails command to execute:

forkConfig = [maxMemory: 1024, minMemory: 64, debug: true, maxPerm: 256]
grails.project.fork = [
   run: forkConfig, // configure settings for the run-app JVM

h4. Changes to Core plugin versioning schemes and the Upgrade command


Core plugins like tomcat and hibernate are no longer versioned the same as the Grails version, instead they are versioned according to the Tomcat and Hibernate version they target. If you are upgrading from Grails 2.2 you need to manually configure the correct Tomcat and Hibernate plugins in BuildConfig. The upgrade command will not do this for you!

plugins {
        // plugins for the build system only
        build ':tomcat:'

// plugins needed at runtime but not for compilation runtime ':hibernate:3.6.10.M3' }


Note that the upgrade command will be deprecated in 2.3 and replaced with a command named use-current-grails-version, which will make no attempts to automatically upgrade Grails applications.

h4. Encoding / Escaping (XSS) Changes


Grails 2.3 includes new features to help prevent XSS attacks. These are enabled by default for new applications, but older applications will require manual intervention. See the section on Cross Site Scripting (XSS) prevention for how to appropriately configure XSS prevention.




Although the Grails development team have tried to keep breakages to a minimum there are a number of items to consider when upgrading a Grails 1.0.x, 1.1.x, 1.2.x, or 1.3.x applications to Grails 2.0. The major changes are described in more detail below, but here's a brief summary of what you might encounter when upgrading from Grails 1.3.x:
Grails開発チームではできる限りの下位互換を心がけていますが、Grails 2.0へ更新する際に、下位バージョンから考慮しなくてはならない内容が幾つか存在します。大きな変更点を以下にまとめます。
  • Dependency resolution has been changed to only use data from the POMs to resolve, this can impact plugins and you may need to republish a plugin with corrected dependency data

* environment bean added by Spring 3.1, which will be auto-wired into properties of the same name.
Spring 3.1によって、同じ名称の環境が environment ビーンが自動追加されます。

* Logging by convention packages have changed, so you may not see the logging output you expect. Update your logging configuration as described below.
  • ロギングDSLのパッケージが変更されたので正常にログ出力がされない場合があります。ログの設定を変更する必要があります。

* HSQLDB has been replaced with H2 as default in-memory database. If you use the former, either change your data source to H2 or add HSQLDB as a runtime dependency.
  • デフォルトのインメモリーデータベースがHSQLDBからH2へ変更になりました。使用している場合はデータソースの設定を変更するか、HSQLDBを依存管理に追加する必要があります。

* The release-plugin command has been removed. You must now install the Release plugin and use its publish-plugin command instead.

* The redirect() method no longer commits the response, so isCommitted() will return false. If you use that method, then call request.isRedirected() instead.
  • redirect()メソッドがレスポンスを返さなくなります。これにより、isCommitted()falseを返す事になります。isCommitted()を使用している場合は、代わりにrequest.isRedirected()を使用しましょう

* The redirect() method now uses the grails.serverURL config setting to generate the redirect URL. You may need to remove the setting, particularly from the development and test environments.
  • redirect()メソッドは、設定のgrails.serverURLを使用してリダイレクトのURLを生成するようになります。developmentとtestの環境設定からgrails.serverURL設定を外す必要があります。

* withFormat() no longer takes account of the request content type. If you want to do something based on the request content type, use request.withFormat().
  • withFormat()がリクエストコンテントタイプを取得しなくなりました。リクエストコンテントタイプでの動作を実装する場合は、request.withFormat()を使用してください。

* Adaptive AJAX tags using Prototype will break. In this situation you must install the new Prototype plugin.
  • Prototypeを使用したAJAXタグは動作しません。必要であれば、Prototypeプラグインをインストールしてください。

* If you install Resources (or it is installed automatically), tags like <g:javascript> won't write anything to the page until you add the <r:layoutResources/> tags to your layout.
  • Resourcesプラグインをインストールした場合(または、自動的にインストールされた場合)、<r:layoutResources/>をレイアウトに記述するまで、<g:javascript>からは何も出力されません。

* Resources adds a '/static' URL, so you may have to update your access control rules accordingly.
  • ResourcesプラグインはURL '/static'を追加します。それに応じたアクセスコントロールを更新する必要があります。

* Some plugins may fail to install because one or more of their dependencies can not be found. If this happens, the plugin probably has a custom repository URL that you need to add to your project's BuildConfig.groovy.
  • 幾つかのプラグインは依存が見つからなかった際にインストールに失敗する場合があります。その場合は、プラグインがカスタムリポジトリURLを使用している可能性があるので、プロジェクトのBuildConfig.groovyに追加する必要があります。

* The behaviour of abstract domain classes has changed, so if you use them you will either have to move the abstract classes to 'src/groovy' or migrate your database schema and data.
  • 抽象ドメインクラスの振る舞いが変更されました。使用している場合は、抽象クラスを'src/groovy'に移動するか、データベースのスキーマとデータを変更する必要があります。

* Criteria queries default to INNER_JOIN for associations rather than OUTER_JOIN. This may affect some of your result data.
  • クライテリアクエリーのデフォルトがOUTER_JOINからINNER_JOINに変更になりました。幾つかの実装結果に影響が出る可能性があります。

* Constraints declared for non-existent properties will now throw an exception.
  • 存在しないプロパティがconstraintsに定義してある場合、例外を投げるようになりました。

* beforeValidate() may be called two or more times during a request, for example once on save() and once just before the view is rendered.
リクエスト中に beforeValidate() が複数回コールされる可能性があります。例としてsave()で1回そしてビューがレンダリングされる直前など。

* Public methods in controllers will now be treated as actions. If you don't want this, make them protected or private.
  • コントローラ内のパブリックメソッドはアクションとして扱われるようになります。アクションとして扱われたくないメソッドは、protectedまたは、privateに変更してください。

* The new unit testing framework won't work with the old GrailsUnitTestCase class hierarchy. Your old tests will continue to work, but if you wish to use the new annotations, do not extend any of the *UnitTestCase classes.
  • 新ユニットテストフレームワークにより、古いGrailsUnitTestCaseクラス階層は使用できません。新しい仕組みを使用しながら古いテスト仕様で動作させるには、*UnitTestCaseを継承しないようにしてください。

* Output from Ant tasks is now hidden by default. If your scripts are using ant.echo(), ant.input(), etc. you might want to use alternative mechanisms for output.
  • Antタスクからの出力はデフォルトで隠すようになりました。ant.echo(), ant.input()等をスクリプトで使用している場合は、出力用の代替機能を使用してください。

* Domain properties of type java.net.URL may no longer work with your existing data. The serialisation mechanism for them appears to have changed. Consider migrating your data and domain models to String.
  • ドメインプロパティでjava.net.URL型を使用している場合は、既存のデータで動作しません。シリアライゼーションの仕組みが変更になったようです。ドメインモデルとデータをStringに変更することを検討してください。

* The Ivy cache location has changed. If you want to use the old location, configure the appropriate global setting (see below) but be aware that you may run into problems running Grails 1.3.x and 2.x projects side by side.
  • Ivyのキャッシュ場所が変更になりました。古い場所を使用したい場合は、グローバル設定で変更することができます。ただし、1.3.x系と2.x系を平行利用する場合は問題が発生します。

* With new versions of various dependencies, some APIs (such as the Servlet API) may have changed. If you have code that implements any of those APIs, you will need to update it. Problems will typically manifest as compilation errors.
  • 多くのライブラリが新バージョンに変更されました。更新されたライブラリを使用している場合は変更が必要となります。

* The following deprecated classes have been removed: grails.web.JsonBuilder and grails.web.OpenRicoBuilder.
  • 次の非推奨クラスが削除されました: grails.web.JsonBuildergrails.web.OpenRicoBuilder

Upgrading to 2.2 from 2.1 or 2.0

Groovy 2.0

Grails 2.2 ships with Groovy 2.0 which has some language level changes that may require changes to your code or plugins that you use.

Dependency resolution

Grails 2.2 no longer uses the BuildConfig of the plugin for dependency resolution and only uses data provided by POMs, this may impact some plugins that had previously incorrectly specified dependency information.

If you don't want to immediately deal with the changes necessary to upgrade, then you can open BuildConfig and set the legacyResolve settings to true:

grails.project.dependency.resolution = {    
    legacyResolve false 

This is not recommended however, as it will re-enable the previous behavior of using both POM data and BuildConfig to resolve dependencies. The most commmon problem you will face is with plugins that express their dependencies in a scope that is not valid inside a POM (example: "build" scope).

Plugins like this will need to be re-publish with a corrected scope of "compile". If you then specify the plugin as "build" scope in your application, transitive compile and runtime scoped dependencies will be converted to "build" scope as well.

Grails 1.3.xからのアップグレード
Upgrading from Grails 1.3.x

Changes to web.xml template

If you have customized the web.xml provided by grails install-templates then you will need to update this customized template with the latest version provided by Grails. Failing to do so will lead to a ClassNotFoundException for the org.codehaus.groovy.grails.web.util.Log4jConfigListener class.
grails install-templatesで提供されたweb.xmlをカスタマイズしている場合は、最新のGrailsで提供される無いように更新する必要が有ります。変更を行わなかった場合は、org.codehaus.groovy.grails.web.util.Log4jConfigListenerクラスのClassNotFoundExceptionを引き起こします。

Groovy 1.8での変更点
Groovy 1.8 Changes

Groovy 1.8 is a little stricter in terms of compilation so you may be required to fix compilation errors in your application that didn't occur under Grails 1.3.x.
Groovy 1.8ではmコンパイルが少し厳しくなっています。そのため、Grails 1.3.xでは発生しなかったコンパイルエラーに対応する必要があります。

Groovy 1.8 also requires that you update many of the libraries that you may be using in your application. Libraries known to require an upgrade include:
さらに、Groovy 1.8では、アプリケーションで使用している幾つかのライブラリを更新する必要があります。解っている更新が必要なライブラリは以下になります。
  • Spock
  • Geb
  • GMock (upgrade unavailable as of this writing)

新 'environment' ビーン
New 'environment' bean

Spring 3.1 adds a new bean with the name 'environment'. It's of type Environment (in package org.springframework.core.env) and it will automatically be autowired into properties with the same name. This seems to cause particular problems with domain classes that have an environment property. In this case, adding the method: Spring 3.1から'environment'という名称の新規ビーンが追加されました。これはEnvironment型(パッケージorg.springframework.core.env)で、同じ名前のプロパティに自動ワイヤーされます。一部のドメインクラスプロパティでenvironmentの名称をもつ物に問題が起きる可能性があります。その場合次のようにメソッドを追加して回避してください:

void setEnvironment(org.springframework.core.env.Environment env) {}
works around the problem.

HSQLDB Has Been Replaced With H2

HSQLDB is still bundled with Grails but is not configured as a default runtime dependency. Upgrade options include replacing HSQLDB references in DataSource.groovy with H2 references or adding HSQLDB as a runtime dependency for the application.

If you want to run an application with different versions of Grails, it's simplest to add HSQLDB as a runtime dependency, which you can do in BuildConfig.groovy:

// Add HSQLDB as a runtime dependency
grails.project.dependency.resolution = {
    inherits("global") {
    repositories {

dependencies { // HSQLDBの依存定義 (Add HSQLDB as a runtime dependency) runtime 'hsqldb:hsqldb:' } }

A default DataSource.groovy which is compatible with H2 looks like this:

dataSource {
    driverClassName = "org.h2.Driver"
    username = "sa"
    password = ""
// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop','update'
            url = "jdbc:h2:mem:devDb"
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:mem:testDb"
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:prodDb"

Another significant difference between H2 and HSQLDB is in the handling of byte[] domain class properties. HSQLDB's default BLOB size is large and so you typically don't need to specify a maximum size. But H2 defaults to a maximum size of 255 bytes! If you store images in the database, the saves are likely to fail because of this. The easy fix is to add a maxSize constraint to the byte[] property:
他にH2とHSQLDBの重大な違いは、ドメインクラスのプロパティで定義した  byte[] の扱いです。HSQLDBでのBLOBのデフォルトサイズは、大きいので大抵最大サイズを定義する必要が無かったかと思います。H2では最大サイズの初期値が255バイトになっているので、調整する必要があります。調整するには、 制約の maxSize を byte[] のプロパティに定義するだけです。

class MyDomain {
    byte[] data

static constraints = { data maxSize: 1024 * 1024 * 2 // 2MB } }

This constraint influences schema generation, so in the above example H2 will have the data column set to BINARY(2097152) by Hibernate.
上記の制約定義でスキーマ生成を変更します。この例では、dataカラムは、 BINARY(2097152) としてHibernateがセットします。

Abstract Inheritance Changes

In previous versions of Grails abstract classes in grails-app/domain were not treated as persistent. This is no longer the case and has a significant impact on upgrading your application. For example consider the following domain model in a Grails 1.3.x application:
以前のバージョンで、 grails-app/domain に存在する抽象クラスは、永続化対象として扱われませんでした。今後は違うため、アプリケーション更新には重大な影響を与えます。例として以下のようなドメインモデルをGrails-1.3.xで持っていたとします。

abstract class Sellable {

} class Book extends Sellable {


In Grails 1.3.x you would get a BOOK table and the properties from the Sellable class would be stored within the BOOK table. However, in Grails 2.x you will get a SELLABLE table and the default table-per-hierarchy inheritance rules apply with all properties of the Book stored in the SELLABLE table.
Grails 1.3.xの場合は、 BOOK テーブルが生成され、BOOKテーブルに Sellable クラスのプロパティも含まれました。Grails 2.0からは、デフォルトのtable-per-hierarchy (クラス階層ごとのテーブル)継承ルールで、 BOOK クラスの全てのプロパティが含まれた SELLABLE テーブルが生成されます。

You have two options when upgrading in this scenario:

  1. Move the abstract Sellable class into the src/groovy package. If the Sellable class is in the src/groovy directory it will no longer be regarded as persistent.
  2. Use the database migration plugin to apply the appropriate changes to the database (typically renaming the table to the root abstract class of the inheritance tree).

  1. 抽象クラス Sellable をsrc/groovyに移動する。src/groovyに移動すれば永続化対象のクラスとしては認識しません。
  2. データベースマイグレーションプラグイン を使用して、データベースに適した変更を行う。(通常はルート抽象クラスのテーブル名称に変更すれば良いです。)

クライテリアクエリのデフォルトがINNER JOINになります
Criteria Queries Default to INNER JOIN

The previous default of LEFT JOIN for criteria queries across associations is now INNER JOIN.
今まではLEFT JOINがデフォルトでした。これからはINNER JOINになります。

Invalid Constraints Now Thrown an Exception

Previously if you defined a constraint on a property that doesn't exist no error would be thrown:
class Person {
    String name
    static constraints = {
        bad nullable:false // invalid property, no error thrown

Now the above code will result in an exception

Logging By Convention Changes

The packages that you should use for Grails artifacts have mostly changed. In particular:

  • service -> services
  • controller -> controllers
  • tagLib -> taglib (case change)
  • bootstrap -> conf
  • dataSource -> conf

  • service -> services
  • controller -> controllers
  • tagLib -> taglib (Lが小文字に)
  • bootstrap -> conf
  • dataSource -> conf

You can find out more about logging by convention in the main part of the user guide, under "Configuring loggers". This change is a side-effect of injecting the log property into artefacts at compile time.
ログの詳細については、 ユーザガイド を参考にしてください。

jQuery Replaces Prototype

The Protoype Javascript library has been removed from Grails core and now new Grails applications have the jQuery plugin configured by default. This will only impact you if you are using Prototype with the adaptive AJAX tags in your application, e.g. <g:remoteLink/> etc, because those tags will break as soon as you upgrade.

To resolve this issue, simply install the Prototype plugin in your application. You can also remove the prototype files from your web-app/js/prototype directory if you want.
この問題は Prototypeプラグイン をインストールすることで解決できます。Prototypeはプラグイン内から参照するようになるので、不用になるweb-app/js/prototypeディレクトリは削除できます。

The Resources Plugin

The Resources plugin is a great new feature of Grails that allows you to manage static web resources better than before, but you do need to be aware that it adds an extra URL at /static. If you have access control in your application, this may mean that the static resources require an authenticated user to load them! Make sure your access rules take account of the /static URL.

Controller Public Methods

As of Grails 2.0, public methods of controllers are now treated as actions in addition to actions defined as traditional Closures. If you were relying on the use of methods for privacy controls or as helper methods then this could result in unexpected behavior. To resolve this issue you should mark all methods of your application that are not to be exposed as actions as private methods.
Grails 2.0からは、今までのクロージャに加えて、コントローラのパブリックメソッドもアクションとして扱われるようになりました。もし補助機能や内部機能としてメソッドを使用している場合は必ずメソッドを private にしてください。

Command Object Constraints

As of Grails 2.0, constrained properties in command object classes are no longer nullable by default. Nullable command object properties must be explicitly configured as such in the same way that nullable persistent properties in domain classes are configured.
Grails 2.0よりコマンドオブジェクトのプロパティ制約はnullableが既存値ではなくなりました。Nullable指定のコマンドオブジェクトプロパティは明示的に指定する必要があります。指定方法はドメインクラスと同じです。

The redirect Method

The redirect method no longer commits the response. The result of this is code that relies of this behavior will break in 2.0. For example:
リダイレクト redirect メソッドがレスポンスを返さなくなります。以下のコードは2.0では動作しなくなります:

redirect action: "next"
if (response.committed) {
    // do something

In this case in Grails 1.3.x and below the response.committed property would return true and the if block will execute. In Grails 2.0 this is no longer the case and you should instead use the new isRedirected() method of the request object:
このケースが1.3.xの場合では、 response.committed プロパティがtrueを返すため if ブロックが実行されます。Grails 1.4では、同等の動きをしないため、代わりに request インスタンスの isRedirected() メソッドを使用します。

redirect action: "next"
if (request.redirected) {
    // do something

Another side-effect of the changes to the redirect method is that it now always uses the grails.serverURL configuration option if it's set. Previous versions of Grails included default values for all the environments, but when upgrading to Grails 2.0 those values more often than not break redirection. So, we recommend you remove the development and test settings for grails.serverURL or replace them with something appropriate for your application.
他のリダイレクトメソッドへの変更による副作用は、 grails.serverURL が設定されていれば常に使用するという点です。以前のバージョンのGrailsではデフォルトの値を保持していました、Grails 2.0に更新するとそれらを参照するために問題が発生します。したがって、test、developmentの定義から grails.serverURL を外すか、妥当な値に設定することを推奨します。

Content Negotiation

As of Grails 2.0 the withFormat method of controllers no longer takes into account the request content type (dictated by the CONTENT_TYPE header), but instead deals exclusively with the response content type (dictated by the ACCEPT header or file extension). This means that if your application has code that relies on reading XML from the request using withFormat this will no longer work:
Grails 2.0からコントローラのwithFormatメソッドは、リクエストのコンテントタイプ(CONTENT_TYPEヘッダ)を評価しなくなりました。これにかわって、レスポンスのコンテントタイプ(ACCEPTヘッダまたはファイル拡張子)が排他的に処理を行います。これによって今までのアプリケーションのwithFormatを使用してリクエストからXMLを読み込む等のコードは動作しなくなります。

def processBook() {
    withFormat {
        xml {
            // read request XML
        html {
            // read request parameters

Instead you use the withFormat method provided on the request object:
withFormat の代わりに、 request オブジェクトで提供されているwithFormatメソッドを使用できます:

def processBook() {
    request.withFormat {
        xml {
            // read request XML
        html {
            // read request parameters

Unit Test Framework

Grails 2 introduces a new unit testing framework that is simpler and behaves more consistently than the old one. The old framework based on the GrailsUnitTestCase class hierarchy is still available for backwards compatibility, but it does not work with the new annotations.
Grails 2では、古い仕様より単純でかつ安定した、新しいユニットテストフレームワークを実装しています。下位互換としてGrailsUnitTestCaseクラス階層をベースとした古いフレームワークも使用可能です。但し、新しい仕組みのアノテーションとは平行利用できません。

Migrating unit tests to the new approach is non-trivial, but recommended. Here are a set of mappings from the old style to the new:

  1. Remove extends *UnitTestCase and add a @TestFor annotation to the class if you're testing a core artifact (controller, tag lib, domain class, etc.) or @TestMixin(GrailsUnitTestMixin) for non-core artifacts and non-artifact classes.
  2. Add @Mock annotation for domain classes that must be mocked and use new MyDomain().save() in place of mockDomain().
  3. Replace references to mockRequest, mockResponse and mockParams with request, response and params.
  4. Remove references to renderArgs and use the view and model properties for view rendering, or response.text for all others.
  5. Replace references to redirectArgs with response.redirectedUrl. The latter takes into account the URL mappings as is a string URL rather than a map of redirect() arguments.
  6. The mockCommandObject() method is no longer needed as Grails automatically detects whether an action requires a command object or not.

  1. コアアーテファクト(コントローラ、タグリブ、ドメインクラス等)のテストの場合は、 extends *UnitTestCaseを削除して、@TestForアノテーションをクラスに追加します。コアアーティファクト以外やアーティファクト以外の場合は、@TestMixin(GrailsUnitTestMixin)アノテーションを追加します。
  2. モックするドメインクラスで、mockDomain()の代わりに、new MyDomain().save()を使用するために、@Mockアノテーションでドメインクラスを指定します。
  3. mockRequestmockResponsemockParamsへの参照をrequestresponseparamsに変更します。
  4. renderArgsを参照している部分を削除して、viewmodelプロパティをビューレンダリング用に、また他はresponse.textを使用するようにします。
  5. redirectArgsは、response.redirectedUrlに変更します。後者はURLマッピングの内容を、redirect()のマップのでは無く、文字列のURLで返します。
  6. mockCommandObject()メソッドは、アクションが必要であれば自動的にコマンドオブジェクトを認識するため必要無くなりました。

There are other differences, but these are the main ones. We recommend that you read the chapter on testing thoroughly to understand everything that has changed.
他にも違いは多数有りますが、これらがメインとなります。chapter on testingをしっかり読んで理解することを推奨します。

Note that the Grails annotations don't need to be imported in your test cases to run them from the command line, but your IDE may need them. So, here are the relevant classes with packages:
  • grails.test.mixin.TestFor
  • grails.test.mixin.TestMixin
  • grails.test.mixin.Mock
  • grails.test.mixin.support.GrailsUnitTestMixin
  • grails.test.mixin.domain.DomainClassUnitTestMixin
  • grails.test.mixin.services.ServiceUnitTestMixin
  • grails.test.mixin.web.ControllerUnitTestMixin
  • grails.test.mixin.web.FiltersUnitTestMixin
  • grails.test.mixin.web.GroovyPageUnitTestMixin
  • grails.test.mixin.web.UrlMappingsUnitTestMixin
  • grails.test.mixin.webflow/WebFlowUnitTestMixin

Note that you're only ever likely to use the first two explicitly. The rest are there for reference.

Command Line Output

Ant output is now hidden by default to keep the noise in the terminal to a minimum. That means if you use ant.echo in your scripts to communicate messages to the user, we recommend switching to an alternative mechanism.
ターミナルの表示を最小にするためにAnt出力は表示されなくなりました。これによりスクリプトでの出力としての ant.echo からのメッセージは表示されなくなります。それに変わる方法に変更することをお勧めします。

For status related messages, you can use the event system:

event "StatusUpdate", ["Some message"]
event "StatusFinal",  ["Some message"]
event "StatusError",  ["Some message"]

For more control you can use the grailsConsole script variable, which gives you access to an instance of GrailsConsole. In particular, you can log information messages with log() or info(), errors and warnings with error() and warning(), and request user input with userInput().
さらなる制御として、api:grails.build.logging.GrailsConsoleインスタンスにアクセスするスクリプト変数 GrailsConsole|api:grails.build.logging.GrailsConsole] を使用することもできます。特に情報のログをとるための、 log()info() 、エラーや警告用に error()warning() を使用したり、ユーザからの入力を要求する場合は userInput() を使用できます。

Custom Plugin Repositories

Many plugins have dependencies, both other plugins and straight JAR libraries. These are often located in Maven Central, the Grails core repository or the Grails Central Plugin Repository in which case applications are largely unaffected if they upgrade to Grails 2. But sometimes such dependencies are located elsewhere and Grails must be told where they can be found.

Due to changes in the way Grails handles the resolution of dependencies, Grails 2.0 requires you to add any such custom repository locations to your project if an affected plugin is to install properly.

Ivy cache location has changed

The default Ivy cache location for Grails has changed. If the thought of yet another cache of JARs on your disk horrifies you, then you can change this in your settings.groovy:

grails.dependency.cache.dir = "${userHome}/.ivy2/cache"

If you do this, be aware that you may run into problems running Grails 2 and earlier versions of Grails side-by-side. These problems can be avoided by excluding "xml-apis" and "commons-digester" from the inherited global dependencies in Grails 1.3 and earlier projects.

URL Domain Properties

If your domain model has any properties of type java.net.URL, they may cease to work once you upgrade to Grails 2. It seems that the default mapping of URL to database column has changed with the new version of Hibernate. This is a tricky problem to solve, but in the long run it's best if you migrate your URL properties to strings. One technique is to use the database migration plugin to add a new text column and then execute some code in BootStrap (using Grails 1.3.x or earlier) to fetch each row of the table as a domain instance, convert the URL properties to string URLs, and then write those values to the new column.

Updated Underlying APIs

Grails 2.0 contains updated dependencies including Servlet 3.0, Tomcat 7, Spring 3.1, Hibernate 3.6 and Groovy 1.8. This means that certain plugins and applications that depend on earlier versions of these APIs may no longer work. For example the Servlet 3.0 HttpServletRequest interface includes new methods, so if a plugin implements this interface for Servlet 2.5 but not for Servlet 3.0 then said plugin will break. The same can be said of any Spring interface.
Grails 2.0では、Servlet 3.0、Tomcat 7、Spring 3.1、Hibernate 3.6、Groovy 1.8などのライブラリを更新しました。以前のバージョンのプラグインなどでこれらのライブラリに依存がある場合動作しなくなります。例としてServlet 3.0の HttpServletRequest インターフェイスは新しい物を多く含んでいます。この逆もあり得るので、Servlet 2.5のインターフェイスで実装され、Servlet 3.0に存在しない機能を持っているプラグインは動作しません。もちろんこの事はSpringなど他のライブラリにも同じ事が言えます。注意しましょう。

Removal of release-plugin

The built in release-plugin command for releases plugins to the central Grails plugin repository has been removed. The new release plugin should be used instead which provides an equivalent publish-plugin command.
プラグインを公式リポジトリに発行するコマンド release-plugin が除去されました。新たに リリースプラグイン を使用して同じ意味を持つ publish-plugin コマンドを使用してください。

Removal of Deprecated Classes

The following deprecated classes have been removed: grails.web.JsonBuilder, grails.web.OpenRicoBuilder
次のクラスが除去されました。 grails.web.JsonBuilder , grails.web.OpenRicoBuilder

Grails 1.2.x からのアップグレード
Upgrading from Grails 1.2.x

Plugin Repositories

As of Grails 1.3, Grails no longer natively supports resolving plugins against secured SVN repositories. The plugin resolution mechanism in Grails 1.2 and below has been replaced by one built on Ivy, the upside of which is that you can now resolve Grails plugins against Maven repositories as well as regular Grails repositories.
Grails 1.3では、認証付きSVNリポジトリ内のプラグイン解決に標準では対応しなくなりました。Grails 1.2以前のプラグイン解決の仕組みは、Ivyをベースに構築された実装により、Grailsのライブラリと同等にMavenリポジトリを対象に、プラグイン解決の仕組みに変更されました。

Ivy supports a much richer set of repository resolvers for resolving plugins, including support for Webdav, HTTP, SSH and FTP. See the section on resolvers in the Ivy docs for all the available options and the section of plugin repositories in the user guide which explains how to configure additional resolvers.
Ivyでは、WebDAV, HTTP, SSHやFTPなど豊富なリポジトリ解決方法があります。利用可能なオプションについてはIvyのドキュメントのリゾルバのセクションを、追加のリゾルバの設定方法については、このユーザーガイドのプラグイン・リポジトリのセクションを参照してください。

If you still need support for resolving plugins against secured SVN repositories then the IvySvn project provides a set of resolvers for SVN repositories.

Grails 1.1.x からのアップグレード
Upgrading from Grails 1.1.x

翻訳チームの判断により、Grails 1.1.xからの更新は翻訳を行いません。ご了承ください。

Plugin paths

In Grails 1.1.x typically a pluginContextPath variable was used to establish paths to plugin resources. For example:
Grails 1.1.xではプラグイン内のリソースを参照するために変数pluginContextPathが、以下のように使用されていました:

<g:resource dir="${pluginContextPath}/images" file="foo.jpg" />

In Grails 1.2 views have been made plugin aware and this is no longer necessary:
Grails 1.2からはプラグイン認識されるため、この変数は不要になりました:

<g:resource dir="images" file="foo.jpg" />

Additionally the above example will no longer link to an application image from a plugin view. To do so change the above to:

<g:resource contextPath="" dir="images" file="foo.jpg" />

The same rules apply to the javascript and render tags.

Tag and Body return values

Tags no longer return java.lang.String instances but instead return a Grails StreamCharBuffer instance. The StreamCharBuffer class implements all the same methods as String but doesn't extend String, so code like this will break:

def foo = body()
if (foo instanceof String) {
    // do something

In these cases you should check for the java.lang.CharSequence interface, which both String and StreamCharBuffer implement:

def foo = body()
if (foo instanceof CharSequence) {
    // do something

New JSONBuilder

There is a new version of JSONBuilder which is semantically different from the one used in earlier versions of Grails. However, if your application depends on the older semantics you can still use the deprecated implementation by setting the following property to true in Config.groovy:


Validation on Flush

Grails now executes validation routines when the underlying Hibernate session is flushed to ensure that no invalid objects are persisted. If one of your constraints (such as a custom validator) executes a query then this can cause an additional flush, resulting in a StackOverflowError. For example:

static constraints = {
    author validator: { a ->
        assert a != Book.findByTitle("My Book").author

The above code can lead to a StackOverflowError in Grails 1.2. The solution is to run the query in a new Hibernate session (which is recommended in general as doing Hibernate work during flushing can cause other issues):

static constraints = {
    author validator: { a ->
        Book.withNewSession {
            assert a != Book.findByTitle("My Book").author

Grails 1.0.xからのアップグレード
Upgrading from Grails 1.0.x

翻訳チームの判断により、Grails 1.0.xからの更新は翻訳を行いません。ご了承ください。

Groovy 1.6

Grails 1.1 and above ship with Groovy 1.6 and no longer supports code compiled against Groovy 1.5. If you have a library that was compiled with Groovy 1.5 you must recompile it against Groovy 1.6 or higher before using it with Grails 1.1.

Java 5.0

Grails 1.1 now no longer supports JDK 1.4, if you wish to continue using Grails then it is recommended you stick to the Grails 1.0.x stream until you are able to upgrade your JDK.

Configuration Changes

1) The setting grails.testing.reports.destDir has been renamed to grails.project.test.reports.dir for consistency.

2) The following settings have been moved from grails-app/conf/Config.groovy to grails-app/conf/BuildConfig.groovy:

    • grails.config.base.webXml
    • grails.project.war.file (renamed from grails.war.destFile)
    • grails.war.dependencies
    • grails.war.copyToWebApp
    • grails.war.resources

3) The grails.war.java5.dependencies option is no longer supported, since Java 5.0 is now the baseline (see above).

4) The use of jsessionid (now considered harmful) is disabled by default. If your application requires jsessionid you can re-enable its usage by adding the following to grails-app/conf/Config.groovy:


5) The syntax used to configure Log4j has changed. See the user guide section on Logging for more information.

Plugin Changes

As of version 1.1, Grails no longer stores plugins inside your PROJECT_HOME/plugins directory by default. This may result in compilation errors in your application unless you either re-install all your plugins or set the following property in grails-app/conf/BuildConfig.groovy:


Script Changes

1) If you were previously using Grails 1.0.3 or below the following syntax is no longer support for importing scripts from GRAILS_HOME:

grailsHome = Ant.antProject.properties."env.GRAILS_HOME"

includeTargets << new File("${grailsHome}/scripts/Bootstrap.groovy")

Instead you should use the new grailsScript method to import a named script:

includeTargets << grailsScript("_GrailsBootstrap")

2) Due to an upgrade of Gant all references to the variable Ant should be changed to ant.

3) The root directory of the project is no longer on the classpath, so loading a resource like this will no longer work:

def stream = getClass().classLoader.getResourceAsStream(

Instead you should use the Java File APIs with the basedir property:

new File("${basedir}/grails-app/conf/my-config.xml").withInputStream { stream ->
    // read the file

Command Line Changes

The run-app-https and run-war-https commands no longer exist and have been replaced by an argument to run-app:

grails run-app -https

Data Mapping Changes

1) Enum types are now mapped using their String value rather than the ordinal value. You can revert to the old behavior by changing your mapping as follows:

static mapping = {
    someEnum enumType:"ordinal"

2) Bidirectional one-to-one associations are now mapped with a single column on the owning side and a foreign key reference. You shouldn't need to change anything; however you should drop column on the inverse side as it contains duplicate data.

REST Support

Incoming XML requests are now no longer automatically parsed. To enable parsing of REST requests you can do so using the parseRequest argument inside a URL mapping:


Alternatively, you can use the new resource argument, which enables parsing by default:


4 設定

It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now. With Grails' default settings you can actually develop an application without doing any configuration whatsoever, as the quick start demonstrates, but it's important to learn where and how to override the conventions when you need to. Later sections of the user guide will mention what configuration settings you can use, but not how to set them. The assumption is that you have at least read the first section of this chapter!
設定より規約(convention-over-configuration)を採用したフレームワークにおいて設定の説明をするのは、なんだかおかしく思えるかもしれません。 クイックスタートにあるように、Grailsのデフォルト設定を使用すると、実際には一切設定をすることなくアプリケーション開発を始めることができますが、必要な時に規約をどこでどのようにオーバーライドするのか学んでおくことは重要です。 これ以降のセクションでは、どんな設定が利用できるかについては言及しますが、どのように設定するかは言及しません。 というのは、少なくともこの章の最初のセクションは読むだろうと仮定しているからです!

4.1 基本設定

For general configuration Grails provides two files:
  • grails-app/conf/BuildConfig.groovy
  • grails-app/conf/Config.groovy

Both of them use Groovy's ConfigSlurper syntax. The first, BuildConfig.groovy, is for settings that are used when running Grails commands, such as compile, doc, etc. The second file, Config.groovy, is for settings that are used when your application is running. This means that Config.groovy is packaged with your application, but BuildConfig.groovy is not. Don't worry if you're not clear on the distinction: the guide will tell you which file to put a particular setting in.
両方ともGroovyのConfigSlurperの構文を使用しています。 1つめのBuildConfig.groovycompiledoc等のようなGrailsコマンドを実行するときに使われる設定です。 2つめのConfig.groovyはアプリケーションを実行するときに使われる設定です。 つまり、Config.groovyはアプリケーションにパッケージされますが、BuildConfig.groovyはされません。 違いがよく分からなくても心配する必要はありません。 どの設定をどのファイルに書くべきかはこのガイドで示していきます。

The most basic syntax is similar to that of Java properties files with dot notation on the left-hand side:

foo.bar.hello = "world"

Note that the value is a Groovy string literal! Those quotes around 'world' are important. In fact, this highlights one of the advantages of the ConfigSlurper syntax over properties files: the property values can be any valid Groovy type, such as strings, integers, or arbitrary objects!
この値がGroovyの文字列リテラルであることに注意してください! 'world'を囲んでいる引用符が重要です。 実際に、これがプロパティファイルに対するConfigSlurperのシンタックスの有利な点の1つを際立たせています。 プロパティの値は文字列や整数、任意のオブジェクトのような、Groovyとして有効な型を取ることができるのです!

Things become more interesting when you have multiple settings with the same base. For example, you could have the two settings
同じベースで複数の設定をすると、もっとおもしろいことになります。 例えば、2つの設定を持つことができます。

foo.bar.hello = "world"
foo.bar.good = "bye"

both of which have the same base: foo.bar. The above syntax works but it's quite repetitive and verbose. You can remove some of that verbosity by nesting properties at the dots:
両方ともfoo.barという同じベースを持っています。 上記の構文は動作しますが、繰り返しがかなり冗長です。 プロパティのドットの箇所でネストして、冗長さを無くすことができます:

foo {
    bar {
        hello = "world"
        good = "bye"

or by only partially nesting them:

foo {
    bar.hello = "world"
    bar.good = "bye"

However, you can't nest after using the dot notation. In other words, this won't work:
しかしながら、ドット区切りの後にネストを使うことはできません。 つまり、これは動作しません:

// Won't work!
foo.bar {
    hello = "world"
    good = "bye"

Within both BuildConfig.groovy and Config.groovy you can access several implicit variables from configuration values:

userHomeLocation of the home directory for the account that is running the Grails application.
grailsHomeLocation of the directory where you installed Grails. If the GRAILS_HOME environment variable is set, it is used.
appNameThe application name as it appears in application.properties.
appVersionThe application version as it appears in application.properties.

For example:

my.tmp.dir = "${userHome}/.grails/tmp"

In addition, BuildConfig.groovy has

grailsVersionThe version of Grails used to build the project.
grailsSettingsAn object containing various build related settings, such as baseDir. It's of type BuildSettings.

and Config.groovy has

grailsApplicationThe GrailsApplication instance.

Those are the basics of adding settings to the configuration file, but how do you access those settings from your own application? That depends on which config you want to read.
ここまでは設定ファイルに設定を追加するための基本についてでしたが、アプリケーション自身からどのようにそれらの設定にアクセスするのでしょうか? それはどの設定を読みたいかによります。

The settings in BuildConfig.groovy are only available from command scripts and can be accessed via the grailsSettings.config property like so:
BuildConfig.groovy内の設定はコマンドスクリプトからしか取得できません。 以下のようにgrailsSettings.configプロパティを経由してアクセスできます:

target(default: "Example command") {
    def maxIterations = grailsSettings.config.myapp.iterations.max

If you want to read runtime configuration settings, i.e. those defined in Config.groovy, use the grailsApplication object, which is available as a variable in controllers and tag libraries:

class MyController {
    def hello() {
        def recipient = grailsApplication.config.foo.bar.hello

render "Hello ${recipient}" } }

and can be easily injected into services and other Grails artifacts:

class MyService {
    def grailsApplication

String greeting() { def recipient = grailsApplication.config.foo.bar.hello return "Hello ${recipient}" } }

As you can see, when accessing configuration settings you use the same dot notation as when you define them.

4.1.1 組込オプション

Grails has a set of core settings that are worth knowing about. Their defaults are suitable for most projects, but it's important to understand what they do because you may need one or more of them later.
Grailsには知っておくべき基本設定の一式があります。 それらのデフォルトは多くのプロジェクトに適していますが、後で設定が必要になった時のために、それが何の設定であるか理解しておくことが重要です。

Build settings


Let's start with some important build settings. Although Grails requires JDK 6 when developing your applications, it is possible to deploy those applications to JDK 5 containers. Simply set the following in BuildConfig.groovy:
いくつかの重要なビルド設定から始めましょう。 アプリケーションを開発するとき、GrailsはJDK 6を必要としますが、それらのアプリケーションをJDK 5で動作しているコンテナへデプロイすることが可能です。 単純にBuildConfig.groovy内で次のように設定します:

grails.project.source.level = "1.5"
grails.project.target.level = "1.5"

Note that source and target levels are different to the standard public version of JDKs, so JDK 5 -> 1.5, JDK 6 -> 1.6, and JDK 7 -> 1.7.
ただし、ソースとターゲットレベルはJDKの標準公開バージョンと異なり、JDK 5は1.5、JDK 6は1.6、そしてJDK 7は1.7となるようにしてください。

In addition, Grails supports Servlet versions 2.5 and above but defaults to 2.5. If you wish to use newer features of the Servlet API (such as 3.0 async support) you should configure the grails.servlet.version setting appropriately:
加えて、Grailsはサーブレットバージョン2.5以上をサポートし、デフォルトは2.5です。 もし(3.0の非同期サポートのような)サーブレットAPIの新しい機能を使いたければ、grails.servlet.versionを適切に設定します:

grails.servlet.version = "3.0"

Runtime settings


On the runtime front, i.e. Config.groovy, there are quite a few more core settings:

  • grails.config.locations - The location of properties files or addition Grails Config files that should be merged with main configuration. See the section on externalised config.
  • grails.enable.native2ascii - Set this to false if you do not require native2ascii conversion of Grails i18n properties files (default: true).
  • grails.views.default.codec - Sets the default encoding regime for GSPs - can be one of 'none', 'html', or 'base64' (default: 'none'). To reduce risk of XSS attacks, set this to 'html'.
  • grails.views.gsp.encoding - The file encoding used for GSP source files (default: 'utf-8').
  • grails.mime.file.extensions - Whether to use the file extension to dictate the mime type in Content Negotiation (default: true).
  • grails.mime.types - A map of supported mime types used for Content Negotiation.
  • grails.serverURL - A string specifying the server URL portion of absolute links, including server name e.g. grails.serverURL="http://my.yourportal.com". See createLink. Also used by redirects.
  • grails.views.gsp.sitemesh.preprocess - Determines whether SiteMesh preprocessing happens. Disabling this slows down page rendering, but if you need SiteMesh to parse the generated HTML from a GSP view then disabling it is the right option. Don't worry if you don't understand this advanced property: leave it set to true.
  • grails.reload.excludes and grails.reload.includes - Configuring these directives determines the reload behavior for project specific source files. Each directive takes a list of strings that are the class names for project source files that should be excluded from reloading behavior or included accordingly when running the application in development with the run-app command. If the grails.reload.includes directive is configured, then only the classes in that list will be reloaded.

  • grails.config.locations - メイン設定にマージされるべきプロパティファイルや追加のGrails設定ファイルの場所です。設定の外部化セクションを参照してください。
  • grails.enable.native2ascii - Grailsのi18nプロパティファイルのnative2ascii変換が必要ない場合はこれをfalseに設定します(デフォルト: true)。
  • grails.views.default.codec - GSPのデフォルトエンコーディング形式を設定します。'none'、'html'、または'base64'のいずれかを設定できます(デフォルト: none)。XSS攻撃によるリスクを減らすためには、これを'html'に設定します。
  • grails.views.gsp.encoding - GSPのソースファイルに使用するファイルエンコーディングです(デフォルト: 'utf-8')。
  • grails.mime.file.extensions - コンテントネゴシエーションにおいてmime typeの判定にファイルの拡張子を使うかどうかです。(デフォルト: true)
  • grails.mime.types - コンテントネゴシエーションで使う、サポートするMIMEタイプのマップです。
  • grails.serverURL - 絶対リンクのサーバURLの部分を指定する文字列です。grails.serverURL="http://my.yourportal.com"のようにサーバ名を含みます。createLinkを参照してください。この設定はリダイレクトにも使われます。
  • grails.views.gsp.sitemesh.preprocess - SiteMeshプリプロセッシングさせるかどうかを決めます。これを無効にするとページのレンダリングが遅くなりますが、GSPビューから生成されたHTMLをパースするためにSiteMeshが必要であれば、無効にすることは正しい選択です。この上級者向けのプロパティを理解していなくても気にする必要はありません。trueのままにしておきましょう。
  • grails.reload.excludesgrails.reload.includes - このディレクティブの設定は、プロジェクト固有のソースファイルに対するリロードの挙動を決めます。それぞれのディレクティブは文字列のリストを取ります。この文字列はrun-appコマンドを使って開発時にアプリケーションを動作させる際、リロード対象から除外または含めるべきプロジェクトのソースファイルのクラス名です。grails.reload.includesディレクティブが設定されている場合、リストにあるクラスだけがリロードされます。

War generation


  • grails.project.war.file - Sets the name and location of the WAR file generated by the war command
  • grails.war.dependencies - A closure containing Ant builder syntax or a list of JAR filenames. Lets you customise what libaries are included in the WAR file.
  • grails.war.copyToWebApp - A closure containing Ant builder syntax that is legal inside an Ant copy, for example "fileset()". Lets you control what gets included in the WAR file from the "web-app" directory.
  • grails.war.resources - A closure containing Ant builder syntax. Allows the application to do any other work before building the final WAR file

  • grails.project.war.file - warコマンドによって生成されるWARファイルの名前と場所を設定します。
  • grails.war.dependencies - Antビルダシンタックスを含むクロージャ、またはJARファイル名のリストです。WARファイルに含まれるライブラリをカスタマイズできます。
  • grails.war.copyToWebApp - "fileset()"等のAntコピーで定義されているAntビルダシンタックスを含むクロージャです。WARファイルに含めるために、"web-app"ディレクトリから何を取得するかを制御できます。
  • grails.war.resources - Antビルダシンタックスを含むクロージャです。最終的にWARファイルをビルドする前に、その他の作業を行うことをアプリケーションに許可します。

For more information on using these options, see the section on deployment

4.1.2 ロギング

The Basics


Grails uses its common configuration mechanism to provide the settings for the underlying Log4j log system, so all you have to do is add a log4j setting to the file grails-app/conf/Config.groovy.
GrailsはGrails自身の共通設定の仕組みを使って、裏にあるLog4jログシステムの設定を提供しています。 なので、log4j設定をgrails-app/conf/Config.groovyファイルに追加するだけです。

So what does this log4j setting look like? Here's a basic example:
では、このlog4jの設定はどのように見えるでしょうか? 基本的な例を示します:

log4j = {
    error  'org.codehaus.groovy.grails.web.servlet',  //  controllers
           'org.codehaus.groovy.grails.web.pages' //  GSP

warn 'org.apache.catalina' }

This says that for loggers whose name starts with 'org.codehaus.groovy.grails.web.servlet' or 'org.codehaus.groovy.grails.web.pages', only messages logged at 'error' level and above will be shown. Loggers with names starting with 'org.apache.catalina' logger only show messages at the 'warn' level and above. What does that mean? First of all, you have to understand how levels work.
このようにすると、名前が「org.codehaus.groovy.grails.web.servlet」または「org.codehaus.groovy.grails.web.pages」で始まるロガーについて、「error」レベル以上で記録されたメッセージのみが見えるようになります。 名前が「org.apache.catalina」で始まるロガーは「warn」レベル以上のメッセージのみが見えます。 どういう意味でしょうか? まず、レベルがどのように動作するか理解しなければなりません。

Logging levels


There are several standard logging levels, which are listed here in order of descending priority:
  1. off
  2. fatal
  3. error
  4. warn
  5. info
  6. debug
  7. trace
  8. all

When you log a message, you implicitly give that message a level. For example, the method log.error(msg) will log a message at the 'error' level. Likewise, log.debug(msg) will log it at 'debug'. Each of the above levels apart from 'off' and 'all' have a corresponding log method of the same name.
メッセージを記録する時、そのメッセージにレベルを暗黙的に与えています。 例えば、log.error(msg)メソッドは「error」レベルでメッセージを記録します。 同様に、log.debug(msg)は「debug」で記録します。 「off」と「all」を除いた上記のレベルには、それぞれに対応する同名のログメソッドがあります。

The logging system uses that message level combined with the configuration for the logger (see next section) to determine whether the message gets written out. For example, if you have an 'org.example.domain' logger configured like so:
メッセージを出力するかどうかを決めるために、ログシステムはロガー(次のセクションを参照)の設定と併せて メッセージ レベルを使います。 例えば、「org.example.domain」ロガーはこのように設定されます:

warn 'org.example.domain'

then messages with a level of 'warn', 'error', or 'fatal' will be written out. Messages at other levels will be ignored.
そうすると、「warn」または「error」、「fatal」レベルのメッセージが出力されるようになります。 その他のレベルのメッセージは無視されます。

Before we go on to loggers, a quick note about those 'off' and 'all' levels. These are special in that they can only be used in the configuration; you can't log messages at these levels. So if you configure a logger with a level of 'off', then no messages will be written out. A level of 'all' means that you will see all messages. Simple.
ロガーに進む前に、「off」と「all」レベルについて簡単に説明します。 これらは設定の中でだけ使うことができ、これらのレベルでメッセージを記録することはできません。 そして、「off」レベルにロガーを設定すると、メッセージが全く出力されなくなります。 「all」レベルは全てのメッセージが見られるようになります。 単純ですね。



Loggers are fundamental to the logging system, but they are a source of some confusion. For a start, what are they? Are they shared? How do you configure them?
ロガーはログシステムにとって必須ですが、混乱のもとです。 まず、ロガーとは何でしょうか?共有されるものでしょうか?どのように設定するのでしょうか?

A logger is the object you log messages to, so in the call log.debug(msg), log is a logger instance (of type Log). These loggers are cached and uniquely identified by name, so if two separate classes use loggers with the same name, those loggers are actually the same instance.
ロガーはメッセージを出力するオブジェクトで、log.debug(msg)という呼び出しにおいては、logが(Log型の)ロガーインスタンスです。 これらのロガーはキャッシュされ、名前によって一意に識別されます。 2つの別々のクラスが同じ名前のロガーを使う場合、そのロガーは実際に同一のインスタンスとなります。

There are two main ways to get hold of a logger:

  1. use the log instance injected into artifacts such as domain classes, controllers and services;
  2. use the Commons Logging API directly.

  1. ドメインクラスやコントローラ、サービスのようなアーティファクトに注入されるlogインスタンスを使う
  2. Commons Logging APIを直接使う

If you use the dynamic log property, then the name of the logger is 'grails.app.<type>.<className>', where type is the type of the artifact, for example 'controllers' or 'services', and className is the fully qualified name of the artifact. For example, if you have this service:
動的なlogプロパティを使う場合、ロガーの名前は「grails.app.<type>.<className>」になります。 このtypeはアーティファクトの種類で、例えば「controllers」や「services」が入ります。 そして、classNameにはそのアーティファクトの完全修飾名が入ります。 例えば、このサービスの場合:

package org.example

class MyService { … }

then the name of the logger will be 'grails.app.services.org.example.MyService'.

For other classes, the typical approach is to store a logger based on the class name in a constant static field:

package org.other

import org.apache.commons.logging.LogFactory

class MyClass { private static final log = LogFactory.getLog(this) … }

This will create a logger with the name 'org.other.MyClass' - note the lack of a 'grails.app.' prefix since the class isn't an artifact. You can also pass a name to the getLog() method, such as "myLogger", but this is less common because the logging system treats names with dots ('.') in a special way.
これは「org.other.MyClass」という名前のロガーが生成されます。 アーティファクトではないクラスには「grails.app.」という接頭辞が付かないことに注意してください。 『myLogger』のような名前をgetLog()メソッドに渡すこともできます。 しかし、ロギングシステムがドット(.)付きの名前を特別な方法で扱うため、これはあまり一般的ではありません。

Configuring loggers


You have already seen how to configure loggers in Grails:

log4j = {
    error  'org.codehaus.groovy.grails.web.servlet'

This example configures loggers with names starting with 'org.codehaus.groovy.grails.web.servlet' to ignore any messages sent to them at a level of 'warn' or lower. But is there a logger with this name in the application? No. So why have a configuration for it? Because the above rule applies to any logger whose name begins with 'org.codehaus.groovy.grails.web.servlet.' as well. For example, the rule applies to both the org.codehaus.groovy.grails.web.servlet.GrailsDispatcherServlet class and the org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest one.
この例では、「org.codehaus.groovy.grails.web.servlet」で始まる名前のロガーに送られてくる、「warn」レベル以下のメッセージは無視するように設定しています。 しかし、アプリケーション上にこの名前のロガーは存在しているのでしょうか?答えはNoです。 ではなぜこんな設定をしているのでしょうか? 上記のルールは、「org.codehaus.groovy.grails.web.servlet.」で 始まる 名前のすべてのロガーにも適用されるからです。 例えば、このルールはorg.codehaus.groovy.grails.web.servlet.GrailsDispatcherServletクラスとorg.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequestクラスの両方に適用されます。

In other words, loggers are hierarchical. This makes configuring them by package much simpler than it would otherwise be.
言い換えると、ロガーは階層的です。 これはパッケージ毎に設定することを、他の設定に比べて非常にシンプルにします。

The most common things that you will want to capture log output from are your controllers, services, and other artifacts. Use the convention mentioned earlier to do that: grails.app.<artifactType>.<className> . In particular the class name must be fully qualifed, i.e. with the package if there is one:
最も多いケースとして、ログ出力を取得したくなるのはコントローラやサービス、その他のアーティファクトです。 先述した「grails.app.<artifactType>.<className>」の規約を使いましょう。 特に、クラス名は完全修飾名にしなければなりません。 すなわち、パッケージが存在していれば含めるようにします:

log4j = {
    // Set level for all application artifacts
    info "grails.app"

// Set for a specific controller in the default package debug "grails.app.controllers.YourController"

// Set for a specific domain class debug "grails.app.domain.org.example.Book"

// Set for all taglibs info "grails.app.taglib" }

The standard artifact names used in the logging configuration are:

  • conf - For anything under grails-app/conf such as BootStrap.groovy (but excluding filters)
  • filters - For filters
  • taglib - For tag libraries
  • services - For service classes
  • controllers - For controllers
  • domain - For domain entities

  • conf - BootStrap.groovyのようなgrails-app/conf配下にあるもの (フィルタは除く)
  • filters - フィルタ
  • taglib - タグライブラリ
  • services - サービスクラス
  • controllers - コントローラ
  • domain - ドメインエンティティ

Grails itself generates plenty of logging information and it can sometimes be helpful to see that. Here are some useful loggers from Grails internals that you can use, especially when tracking down problems with your application:
Grails自身がたくさんのロギング情報を生成しており、ときどき役立つことがあります。 特にアプリケーションの問題を追跡するときに利用可能な、Grails内部の便利なロガーを示します:

  • org.codehaus.groovy.grails.commons - Core artifact information such as class loading etc.
  • org.codehaus.groovy.grails.web - Grails web request processing
  • org.codehaus.groovy.grails.web.mapping - URL mapping debugging
  • org.codehaus.groovy.grails.plugins - Log plugin activity
  • grails.spring - See what Spring beans Grails and plugins are defining
  • org.springframework - See what Spring is doing
  • org.hibernate - See what Hibernate is doing

  • org.codehaus.groovy.grails.commons - クラスローディング等のようなコアとなるアーティファクト情報
  • org.codehaus.groovy.grails.web - GrailsのWebリクエスト処理
  • org.codehaus.groovy.grails.web.mapping - URLマッピングのデバッグ
  • org.codehaus.groovy.grails.plugins - プラグインの動作ログ
  • grails.spring - GrailsとプラグインがどんなSpringビーンを定義しているか
  • org.springframework - Springが何をするのか
  • org.hibernate - Hibernateが何をするのか

So far, we've only looked at explicit configuration of loggers. But what about all those loggers that don't have an explicit configuration? Are they simply ignored? The answer lies with the root logger.
ここまで、明示的なロガー設定についてだけ見てきました。 しかし、明示的な設定を 持たない すべてのロガーについてはどうでしょうか? 単純に無視されるのでしょうか? その答えはルートロガーにあります。

The Root Logger


All logger objects inherit their configuration from the root logger, so if no explicit configuration is provided for a given logger, then any messages that go to that logger are subject to the rules defined for the root logger. In other words, the root logger provides the default configuration for the logging system.
すべてのロガーオブジェクトは設定をルートロガーから継承しています。 よって、指定されたロガーに明示的な設定が与えられない場合、そのロガーへのメッセージはルートロガーで定義されたルールに従います。 言い換えると、ルートロガーはロギングシステムのデフォルト設定を提供します。

Grails automatically configures the root logger to only handle messages at 'error' level and above, and all the messages are directed to the console (stdout for those with a C background). You can customise this behaviour by specifying a 'root' section in your logging configuration like so:
Grailsは「error」レベル以上のメッセージだけを扱うように、ルートロガーを自動的に設定します。 そして、すべてのメッセージはコンソール(C言語的に言うと標準出力)に向けられます。 次のようにロギング設定に「root」セクションを定義することによって、挙動をカスタマイズできます:

log4j = {
    root {

The above example configures the root logger to log messages at 'info' level and above to the default console appender. You can also configure the root logger to log to one or more named appenders (which we'll talk more about shortly):
上記の例は「info」レベル以上のメッセージをデフォルトのコンソールアペンダに記録するよう、ルートロガーを設定します。 1つ以上の名前の付いたアペンダに対してロギングするように、ルートロガーを設定することもできます。(アペンダについてはすぐ後で詳しく説明します):

log4j = {
    appenders {
        file name:'file', file:'/var/logs/mylog.log'
    root {
        debug 'stdout', 'file'

In the above example, the root logger will log to two appenders - the default 'stdout' (console) appender and a custom 'file' appender.

For power users there is an alternative syntax for configuring the root logger: the root org.apache.log4j.Logger instance is passed as an argument to the log4j closure. This lets you work with the logger directly:
パワーユーザ向けに、ルートロガーを設定するための別の構文があります。 log4jクロージャの引数としてルートorg.apache.log4j.Loggerインスタンスが渡されます。 これでロガーを直接操作できます:

log4j = { root ->
    root.level = org.apache.log4j.Level.DEBUG

For more information on what you can do with this Logger instance, refer to the Log4j API documentation.

Those are the basics of logging pretty well covered and they are sufficient if you're happy to only send log messages to the console. But what if you want to send them to a file? How do you make sure that messages from a particular logger go to a file but not the console? These questions and more will be answered as we look into appenders.
ここまででロギングの基本をほぼカバーしています。 ログメッセージをコンソールに出力するだけでよいのであれば、これで十分でしょう。 しかし、ファイルに送りたい場合はどうでしょうか? どのようにして、特定のロガーからのメッセージをコンソールではなくファイルに対して送るように設定するのでしょうか? これらの疑問、またはそれ以上についても、アペンダを調べることで、答えが得られるでしょう。



Loggers are a useful mechanism for filtering messages, but they don't physically write the messages anywhere. That's the job of the appender, of which there are various types. For example, there is the default one that writes messages to the console, another that writes them to a file, and several others. You can even create your own appender implementations!
ロガーはメッセージをフィルタリングするために役立つ仕組みです。 しかし、どこにもメッセージを物理的に出力できません。 それはアペンダの役割であり、アペンダには様々な種類があります。 例えば、メッセージをコンソールに出力するデフォルトアペンダや、ファイルに出力するアペンダなど色々あります。 自分でアペンダを実装することすらできます!

This diagram shows how they fit into the logging pipeline:

As you can see, a single logger may have several appenders attached to it. In a standard Grails configuration, the console appender named 'stdout' is attached to all loggers through the default root logger configuration. But that's the only one. Adding more appenders can be done within an 'appenders' block:
見ての通り、1つのロガーに色々なアペンダが繋がっています。 Grailsの標準の設定では、stdoutという名前のコンソールアペンダが、ルートロガーの設定を通じて全てのロガーに繋がっています。 しかし、それ以外のアペンダはありません。 appendersブロックで、さらにアペンダを追加することができます:

log4j = {
    appenders {
        rollingFile name: "myAppender",
                    maxFileSize: 1024,
                    file: "/tmp/logs/myApp.log"

The following appenders are available by default:

jdbcJDBCAppenderLogs to a JDBC connection.
consoleConsoleAppenderLogs to the console.
fileFileAppenderLogs to a single file.
rollingFileRollingFileAppenderLogs to rolling files, for example a new file each day.

Each named argument passed to an appender maps to a property of the underlying Appender implementation. So the previous example sets the name, maxFileSize and file properties of the RollingFileAppender instance.
アペンダに渡されるそれぞれの名前付き引数は、Appender実装の下にあるプロパティに対応しています。 つまり、前の例はRollingFileAppenderのインスタンスのnamemaxFileSizefileプロパティを設定しています。

You can have as many appenders as you like - just make sure that they all have unique names. You can even have multiple instances of the same appender type, for example several file appenders that log to different files.
好きなだけ多くのアペンダを持つことができます。 ただし、アペンダはすべてユニークな名前になるようにしてください。 例えば、異なるファイルに出力する複数のファイルアペンダのように、同じアペンダ型の複数のインスタンスを持つこともできます。

If you prefer to create the appender programmatically or if you want to use an appender implementation that's not available in the above syntax, simply declare an appender entry with an instance of the appender you want:

import org.apache.log4j.*

log4j = { appenders { appender new RollingFileAppender( name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log") } }

This approach can be used to configure JMSAppender, SocketAppender, SMTPAppender, and more.

Once you have declared your extra appenders, you can attach them to specific loggers by passing the name as a key to one of the log level methods from the previous section:

error myAppender: "grails.app.controllers.BookController"

This will ensure that the 'grails.app.controllers.BookController' logger sends log messages to 'myAppender' as well as any appenders configured for the root logger. To add more than one appender to the logger, then add them to the same level declaration:
この設定は、grails.app.controllers.BookControllerのロガーが、ルートロガーによって設定されたアペンダだけでなく、myAppenderにもログメッセージを送るようにします。 1つ以上のアペンダをロガーに追加するには、同じレベルの宣言に追加します:

error myAppender:      "grails.app.controllers.BookController",
      myFileAppender:  ["grails.app.controllers.BookController",
      rollingFile:     "grails.app.controllers.BookController"

The above example also shows how you can configure more than one logger at a time for a given appender (myFileAppender) by using a list.

Be aware that you can only configure a single level for a logger, so if you tried this code:
ロガーにはひとつのレベルしか設定できないことに注意してください。 なので、次のコードを試すと:

error myAppender:      "grails.app.controllers.BookController"
debug myFileAppender:  "grails.app.controllers.BookController"
fatal rollingFile:     "grails.app.controllers.BookController"

you'd find that only 'fatal' level messages get logged for 'grails.app.controllers.BookController'. That's because the last level declared for a given logger wins. What you probably want to do is limit what level of messages an appender writes.
grails.app.controllers.BookControllerのために「fatal」レベルのメッセージだけを記録するというのがわかるでしょう。 特定のロガーに対して宣言した最後のレベルが勝つためです。 おそらく行いたいことは、アペンダが書き込むメッセージのレベルを制限することです。

An appender that is attached to a logger configured with the 'all' level will generate a lot of logging information. That may be fine in a file, but it makes working at the console difficult. So we configure the console appender to only write out messages at 'info' level or above:
「all」レベルで設定されたロガーに繋がれたアペンダは、多くのロギング情報を生成するでしょう。 ファイルに出力する分には良いのですが、コンソール上での作業が難しくなってしまいます。 そのため、「info」レベル以上のメッセージだけ出力するようにコンソールアペンダを設定します:

log4j = {
    appenders {
        console name: "stdout", threshold: org.apache.log4j.Level.INFO

The key here is the threshold argument which determines the cut-off for log messages. This argument is available for all appenders, but do note that you currently have to specify a Level instance - a string such as "info" will not work.
ここでのポイントはthreshold引数でログメッセージを遮断するか決めることです。 この引数は全てのアペンダで利用可能ですが、Levelインスタンスを指定する必要があることに注意してください。 infoのような文字列では動作しません。

Custom Layouts


By default the Log4j DSL assumes that you want to use a PatternLayout. However, there are other layouts available including:
デフォルトでLog4jのDSLは、PatternLayoutを使うことを前提としています。 しかし、以下のような他のレイアウトも利用可能です:

  • xml - Create an XML log file
  • html - Creates an HTML log file
  • simple - A simple textual log
  • pattern - A Pattern layout

  • xml - XMLログファイルを作成
  • html - HTMLログファイルを作成
  • simple - シンプルなテキストログ
  • pattern - パターンレイアウト

You can specify custom patterns to an appender using the layout setting:

log4j = {
    appenders {
        console name: "customAppender",
                layout: pattern(conversionPattern: "%c{2} %m%n")

This also works for the built-in appender "stdout", which logs to the console:

log4j = {
    appenders {
        console name: "stdout",
                layout: pattern(conversionPattern: "%c{2} %m%n")

Environment-specific configuration


Since the logging configuration is inside Config.groovy, you can put it inside an environment-specific block. However, there is a problem with this approach: you have to provide the full logging configuration each time you define the log4j setting. In other words, you cannot selectively override parts of the configuration - it's all or nothing.
ロギングの設定はConfig.groovy内にあるため、環境ごとのブロックの内側にその設定一式を記述できます。 しかし、この方法には問題があります。 環境ごとにlog4jの完全なロギング設定を記述しなければならないのです。 言い換えると、設定の特定の部分だけ都合良く上書きすることができません。 全部書くか、まったく書かないかのどちらかしかありません。

To get around this, the logging DSL provides its own environment blocks that you can put anywhere in the configuration:

log4j = {
    appenders {
        console name: "stdout",
                layout: pattern(conversionPattern: "%c{2} %m%n")

environments { production { rollingFile name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log" } } }

root { //… }

// other shared config info "grails.app.controller"

environments { production { // Override previous setting for 'grails.app.controller' error "grails.app.controllers" } } }

The one place you can't put an environment block is inside the root definition, but you can put the root definition inside an environment block.
唯一root定義 では環境ブロックが使用できませんが、代わりに環境ブロック内へroot定義を配置してください。

Full stacktraces


When exceptions occur, there can be an awful lot of noise in the stacktrace from Java and Groovy internals. Grails filters these typically irrelevant details and restricts traces to non-core Grails/Groovy class packages.
例外が発生した場合、スタックトレース内にはJavaとGroovy内部から恐しいほどたくさんのノイズが発生しています。 Grailsはそれら一般的に重要でない詳細なスタックトレースをフィルタし、主要なGrails/Groovyクラスのパッケージでないスタックトレースを制限します。

When this happens, the full trace is always logged to the StackTrace logger, which by default writes its output to a file called stacktrace.log. As with other loggers though, you can change its behaviour in the configuration. For example if you prefer full stack traces to go to the console, add this entry:
この時、フルスタックトレースは常にStackTraceロガーへ出力されます。 デフォルトはstacktrace.logと呼ばれるファイルへの出力です。 他のロガーと同じように、設定でこの振る舞いを変更できます。 例えば、フルスタックトレースをコンソールに出力したい場合、次の設定を追加します:

error stdout: "StackTrace"

This won't stop Grails from attempting to create the stacktrace.log file - it just redirects where stack traces are written to. An alternative approach is to change the location of the 'stacktrace' appender's file:
これによって、Grailsがstacktrace.logファイルを作成しなくなるわけではありません。 単にスタックトレースが書かれるべき場所を変更するだけです。 別の方法はstacktraceアペンダのファイル場所を変更することです:

log4j = {
    appenders {
        rollingFile name: "stacktrace", maxFileSize: 1024,
                    file: "/var/tmp/logs/myApp-stacktrace.log"

or, if you don't want to the 'stacktrace' appender at all, configure it as a 'null' appender:

log4j = {
    appenders {
        'null' name: "stacktrace"

You can of course combine this with attaching the 'stdout' appender to the 'StackTrace' logger if you want all the output in the console.

Finally, you can completely disable stacktrace filtering by setting the grails.full.stacktrace VM property to true:

grails -Dgrails.full.stacktrace=true run-app

Masking Request Parameters From Stacktrace Logs


When Grails logs a stacktrace, the log message may include the names and values of all of the request parameters for the current request. To mask out the values of secure request parameters, specify the parameter names in the grails.exceptionresolver.params.exclude config property:
Grailsでスタックトレースのログを出力する場合、ログメッセージには現在のリクエストに対するリクエストパラメータのすべての名前と値が含まれるかもしれません。 セキュアなリクエストパラメータの値をマスクするには、grails.exceptionresolver.params.excludeの設定値にパラメータ名を指定します。

grails.exceptionresolver.params.exclude = ['password', 'creditCard']

Request parameter logging may be turned off altogether by setting the grails.exceptionresolver.logRequestParameters config property to false. The default value is true when the application is running in DEVELOPMENT mode and false for all other modes.
grails.exceptionresolver.logRequestParametersの設定値にfalseを設定すると、リクエストパラメータのロギングが完全に停止します。 デフォルト値は、DEVELOPMENTモードでアプリケーションを起動している場合はtrue、それ以外のモードではfalseになります。


Logger inheritance


Earlier, we mentioned that all loggers inherit from the root logger and that loggers are hierarchical based on '.'-separated terms. What this means is that unless you override a parent setting, a logger retains the level and the appenders configured for that parent. So with this configuration:
以前に、全てのロガーはルートロガーを継承し、そしてロガーは「.」を区切りとした階層構造を持っていることを説明しました。 これは親の設定を上書きする場合を除き、ロガーは親のログレベルとアペンダの設定を保持することを意味します。 次の設定では:

log4j = {
    appenders {
        file name:'file', file:'/var/logs/mylog.log'
    root {
        debug 'stdout', 'file'

all loggers in the application will have a level of 'debug' and will log to both the 'stdout' and 'file' appenders. What if you only want to log to 'stdout' for a particular logger? Change the 'additivity' for a logger in that case.
アプリケーション内のすべてのロガーが「debug」レベルに設定され、そしてstdoutアペンダとfileアペンダの両方にログが出力されます。 もし特定のロガーに対してのみstdoutにログを出力したい場合はどうすればよいでしょう?このような場合は、ロガーに対してadditivityを変更してください。

Additivity simply determines whether a logger inherits the configuration from its parent. If additivity is false, then its not inherited. The default for all loggers is true, i.e. they inherit the configuration. So how do you change this setting? Here's an example:
この追加設定はロガーが親から設定を継承するかを決めます。 もしこの設定がfalseの場合、親から設定を継承しません。 すべてのロガーのデフォルトはtrueで親の設定を継承します。 この設定をどのように変更するのでしょうか? 以下に例を示します:

log4j = {
    appenders {
    root {

info additivity: false stdout: ["grails.app.controllers.BookController", "grails.app.services.BookService"] }

So when you specify a log level, add an 'additivity' named argument. Note that you when you specify the additivity, you must configure the loggers for a named appender. The following syntax will not work:
このように、ログレベルを指定する際にadditivityという名前の引数を追加します。 additivityを指定するときは、名前付きのアペンダに対してロガーの設定をしなければなりません。 例えば以下の構文では正しく動作 しません :

info additivity: false, ["grails.app.controllers.BookController",

Customizing stack trace printing and filtering


Stacktraces in general and those generated when using Groovy in particular are quite verbose and contain many stack frames that aren't interesting when diagnosing problems. So Grails uses a implementation of the org.codehaus.groovy.grails.exceptions.StackTraceFilterer interface to filter out irrelevant stack frames. To customize the approach used for filtering, implement that interface in a class in src/groovy or src/java and register it in Config.groovy:
Groovyを個別で使用した場合に生成されるスタックトレースは、とても冗長で問題解析に関係のないたくさんのスタックフレームが含まれています。 Grailsは無関係なスタックフレームを取り除くためにorg.codehaus.groovy.grails.exceptions.StackTraceFiltererインタフェースの実装を使用しています。このフィルタリング方法をカスタマイズするには、src/groovyまたはsrc/javaにインタフェースの実装クラスを配置し、そのクラスをConfig.groovyで登録します:

grails.logging.stackTraceFiltererClass =

In addition, Grails customizes the display of the filtered stacktrace to make the information more readable. To customize this, implement the org.codehaus.groovy.grails.exceptions.StackTracePrinter interface in a class in src/groovy or src/java and register it in Config.groovy:
さらに、Grailsはより情報が読みやすくなるようフィルタしたスタックトレースの表示を変更しています。 これをカスタマイズするには、src/groovyまたはsrc/javaorg.codehaus.groovy.grails.exceptions.StackTracePrinterインタフェースの実装クラスを配置し、そのクラスをConfig.groovyで登録します:

grails.logging.stackTracePrinterClass =

Finally, to render error information in the error GSP, an HTML-generating printer implementation is needed. The default implementation is org.codehaus.groovy.grails.web.errors.ErrorsViewStackTracePrinter and it's registered as a Spring bean. To use your own implementation, either implement the org.codehaus.groovy.grails.exceptions.StackTraceFilterer directly or subclass ErrorsViewStackTracePrinter and register it in grails-app/conf/spring/resources.groovy as:
最後に、エラーGSP内にエラー情報をレンダリングするために、HTMLを生成し出力する実装が必要です。 デフォルト実装はorg.codehaus.groovy.grails.web.errors.ErrorsViewStackTracePrinterで、これはSpringビーンとして登録されています。 独自の実装を使うには、org.codehaus.groovy.grails.exceptions.StackTraceFiltererを直接実装するか、ErrorsViewStackTracePrinterのサブクラスとして実装し、grails-app/conf/spring/resources.groovyでそれを登録します:

import com.yourcompany.yourapp.MyErrorsViewStackTracePrinter

beans = {

errorsViewStackTracePrinter(MyErrorsViewStackTracePrinter, ref('grailsResourceLocator')) }

Alternative logging libraries


By default, Grails uses Log4J to do its logging. For most people this is absolutely fine, and many users don't even care what logging library is used. But if you're not one of those and want to use an alternative, such as the JDK logging package or logback, you can do so by simply excluding a couple of dependencies from the global set and adding your own:
デフォルトでは、GrailsはロギングにLog4Jを使用します。 大抵のユーザにとってはLog4Jで十分で、ロギングライブラリに何が使われているかを気にしません。 しかし、もしそうではなくJDKのロギングパッケージlogbackといった異なるロギングライブラリが使いたい場合、グローバルな設定からいくつかの依存関係を単に取り除き、必要な依存関係を追加します:

grails.project.dependency.resolution = {
    inherits("global") {
        excludes "grails-plugin-logging", "log4j"
    dependencies {
        runtime "ch.qos.logback:logback-core:0.9.29"

If you do this, you will get unfiltered, standard Java stacktraces in your log files and you won't be able to use the logging configuration DSL that's just been described. Instead, you will have to use the standard configuration mechanism for the library you choose.
もしこの設定をした場合、ログファイル内ではフィルタされてない通常のJavaスタックトレースが出力され、そしてDSLで書かれたロギング設定が使用できなくなります。 代わりに、選択したライブラリで用意されている標準的な設定方法を使わなければなりません。

4.1.3 GORM

Grails provides the following GORM configuration options:

* grails.gorm.failOnError - If set to true, causes the save() method on domain classes to throw a grails.validation.ValidationException if validation fails during a save. This option may also be assigned a list of Strings representing package names. If the value is a list of Strings then the failOnError behavior will only be applied to domain classes in those packages (including sub-packages). See the save method docs for more information.
  • grails.gorm.failOnError = trueに設定すると、保存中にバリデーションが失敗した場合、ドメインクラスのsave()メソッドはgrails.validation.ValidationExceptionをスローするようになります。

このオプションには、パッケージ名のリストを指定することもできます。 値が文字列のリストである場合、failOnErrorの挙動は指定されたパッケージの(サブパッケージを含む)ドメインクラスのみに適用されます。 詳細については、saveメソッドのドキュメントを参照してください。

For example, to enable failOnError for all domain classes:


and to enable failOnError for domain classes by package:

grails.gorm.failOnError = ['com.companyname.somepackage',

* grails.gorm.autoFlush = If set to true, causes the merge, save and delete methods to flush the session, replacing the need to explicitly flush using save(flush: true).
  • grails.gorm.autoFlush = trueにセットすると、save(flush: true)を使用して明示的にフラッシュする必要がなくなり、mergesavedeleteメソッドはセッションをフラッシュするようになります。

4.2 環境

h4. Per Environment Configuration


Grails supports the concept of per environment configuration. The Config.groovy, DataSource.groovy, and BootStrap.groovy files in the grails-app/conf directory can use per-environment configuration using the syntax provided by ConfigSlurper. As an example consider the following default DataSource definition provided by Grails:
Grailsは環境ごとで設定値を変更する概念をサポートしています。grails-app/confディレクトリ内のConfig.groovy, DataSource.groovy,BootStrap.groovyファイルはConfigSlurperによって提供される構文を使用して、環境ごとの設定を行うことができます。次の例では、Grailsによって与えられるデフォルトのDataSource定義について記述しています。

dataSource {
    pooled = false
    driverClassName = "org.h2.Driver"
    username = "sa"
    password = ""
environments {
    development {
        dataSource {
            dbCreate = "create-drop"
            url = "jdbc:h2:mem:devDb"
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:mem:testDb"
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:prodDb"

Notice how the common configuration is provided at the top level and then an environments block specifies per environment settings for the dbCreate and url properties of the DataSource.

h4. Packaging and Running for Different Environments


Grails' command line has built in capabilities to execute any command within the context of a specific environment. The format is:

grails [environment] [command name]

In addition, there are 3 preset environments known to Grails: dev, prod, and test for development, production and test. For example to create a WAR for the test environment you wound run:

grails test war

To target other environments you can pass a grails.env variable to any command:

grails -Dgrails.env=UAT run-app

h4. Programmatic Environment Detection


Within your code, such as in a Gant script or a bootstrap class you can detect the environment using the Environment class:

import grails.util.Environment


switch (Environment.current) { case Environment.DEVELOPMENT: configureForDevelopment() break case Environment.PRODUCTION: configureForProduction() break }

h4. Per Environment Bootstrapping


It's often desirable to run code when your application starts up on a per-environment basis. To do so you can use the grails-app/conf/BootStrap.groovy file's support for per-environment execution:

def init = { ServletContext ctx ->
    environments {
        production {
            ctx.setAttribute("env", "prod")
        development {
            ctx.setAttribute("env", "dev")
    ctx.setAttribute("foo", "bar")

h4. Generic Per Environment Execution

The previous BootStrap example uses the grails.util.Environment class internally to execute. You can also use this class yourself to execute your own environment specific logic:

Environment.executeForCurrentEnvironment {
    production {
        // do something in production
    development {
        // do something only in development

4.3 データソース

Since Grails is built on Java technology setting up a data source requires some knowledge of JDBC (the technology that doesn't stand for Java Database Connectivity).
Grailsはデータソースの設定がJava技術で構築されているため、ある程度JDBC(Java DataBase Connectivityの略ではない)の知識が必要になります。

If you use a database other than H2 you need a JDBC driver. For example for MySQL you would need Connector/J
もしH2以外のデータベースを使うなら、JDBCドライバが必要になります。例えばMySQLであればConnector/J が必要になります。

Drivers typically come in the form of a JAR archive. It's best to use Ivy to resolve the jar if it's available in a Maven repository, for example you could add a dependency for the MySQL driver like this:

grails.project.dependency.resolution = {
    log "warn"
    repositories {
    dependencies {
        runtime 'mysql:mysql-connector-java:5.1.16'

Note that the built-in mavenCentral() repository is included here since that's a reliable location for this library.

If you can't use Ivy then just put the JAR in your project's lib directory.

Once you have the JAR resolved you need to get familiar Grails' DataSource descriptor file located at grails-app/conf/DataSource.groovy. This file contains the dataSource definition which includes the following settings:

* driverClassName - The class name of the JDBC driver
  • username - The username used to establish a JDBC connection
  • password - The password used to establish a JDBC connection
  • url - The JDBC URL of the database
  • dbCreate - Whether to auto-generate the database from the domain model - one of 'create-drop', 'create', 'update' or 'validate'
  • pooled - Whether to use a pool of connections (defaults to true)
  • logSql - Enable SQL logging to stdout
  • formatSql - Format logged SQL
  • dialect - A String or Class that represents the Hibernate dialect used to communicate with the database. See the org.hibernate.dialect package for available dialects.
  • readOnly - If true makes the DataSource read-only, which results in the connection pool calling setReadOnly(true) on each Connection
  • persistenceInterceptor - The default datasource is automatically wired up to the persistence interceptor, other datasources are not wired up automatically unless this is set to true
  • properties - Extra properties to set on the DataSource bean. See the Commons DBCP BasicDataSource documentation.
  • driverClassName - JDBCドライバのクラス名
  • username - JDBCコネクションの接続に使用するユーザ名
  • password - JDBCコネクションの接続に使用するパスワード
  • url - データベースのJDBC URL
  • dbCreate - ドメインモデルからデータベースを自動で生成するか。'create-drop'、'create'、'update'、もしくは'validate'の中から1つ指定
  • pooled - コネクションプールを使うか(デフォルトではtrue)
  • logSql - 標準出力へのSQLロギングを有効にするか
  • formatSql - SQLログをフォーマットするか
  • dialect - データベースの通信に使用されるHibernateの方言を表す文字型かクラス。利用できる方言はorg.hibernate.dialectパッケージを参照
  • readOnly - trueにした場合は読み取り専用のデータソースとなり、各ConnectionsetReadOnly(true)がコネクションプールより呼ばれる
  • persistenceInterceptor - The default datasource is automatically wired up to the persistence interceptor, other datasources are not wired up automatically unless this is set to true
  • properties - DataSourceビーンを設定するための追加プロパティ。Commons DBCP BasicDataSourceドキュメント参照
  • A typical configuration for MySQL may be something like:

    dataSource {
        pooled = true
        dbCreate = "update"
        url = "jdbc:mysql://localhost/yourDB"
        driverClassName = "com.mysql.jdbc.Driver"
        dialect = org.hibernate.dialect.MySQL5InnoDBDialect
        username = "yourUser"
        password = "yourPassword"

    When configuring the DataSource do not include the type or the def keyword before any of the configuration settings as Groovy will treat these as local variable definitions and they will not be processed. For example the following is invalid:

    dataSource {
        boolean pooled = true // type declaration results in ignored local variable

    Example of advanced configuration using extra properties:
    dataSource {
        pooled = true
        dbCreate = "update"
        url = "jdbc:mysql://localhost/yourDB"
        driverClassName = "com.mysql.jdbc.Driver"
        dialect = org.hibernate.dialect.MySQL5InnoDBDialect
        username = "yourUser"
        password = "yourPassword"
        properties {
            maxActive = 50
            maxIdle = 25
            minIdle = 5
            initialSize = 5
            minEvictableIdleTimeMillis = 60000
            timeBetweenEvictionRunsMillis = 60000
            maxWait = 10000
            validationQuery = "/* ping */"

    h4. More on dbCreate


    Hibernate can automatically create the database tables required for your domain model. You have some control over when and how it does this through the dbCreate property, which can take these values:

    create* - Drops the existing schemaCreates the schema on startup, dropping existing tables, indexes, etc. first.
    • create-drop - Same as create, but also drops the tables when the application shuts down cleanly.
    • update - Creates missing tables and indexes, and updates the current schema without dropping any tables or data. Note that this can't properly handle many schema changes like column renames (you're left with the old column containing the existing data).
    • validate - Makes no changes to your database. Compares the configuration with the existing database schema and reports warnings.
    • any other value - does nothing
  • create - 起動時に既存のテーブルやインデックスなどを削除することで、既存のスキーマを削除する
  • create-drop - createと同じだが、アプリケーションを停止させた時にテーブルを削除する
  • update - テーブルやデータなどを削除することなく、現在のスキーマを更新する形で存在しないテーブルやインデックスを作成する。これはカラムのリネームのような多くのスキーマ変更を正確に処理できないことに注意してください(既存のデータを含む、古い列が残ってしまう)
  • validate - データベースは変更されません。既存のデータベースとスキーマを比較し、警告を出します
  • any other value - 何もしません
  • You can also remove the dbCreate setting completely, which is recommended once your schema is relatively stable and definitely when your application and database are deployed in production. Database changes are then managed through proper migrations, either with SQL scripts or a migration tool like Liquibase (the Database Migration plugin uses Liquibase and is tightly integrated with Grails and GORM).
    dbCreate設定を完全に削除することもできます。それは、アプリケーションとデータベースが本番環境にデプロイされている場合、スキーマが比較的安定してきた段階で推奨されています。データベースの変更は、SQLスクリプトやLiquibaseのようなマイグレーションツールのどちらかで、適切にマイグレーションを管理してください。(Database Migration プラグインはLiquibaseを使用し、GrailsやGORMと統合されます。)

    4.3.1 データソースと環境

    The previous example configuration assumes you want the same config for all environments: production, test, development etc.
    これまでの例ではすべての環境(production, test, developmentなど)で同じ設定を行うことを想定していました。

    Grails' DataSource definition is "environment aware", however, so you can do:

    dataSource {
        pooled = true
        driverClassName = "com.mysql.jdbc.Driver"
        dialect = org.hibernate.dialect.MySQL5InnoDBDialect
        // other common settings here

    environments { production { dataSource { url = "jdbc:mysql://liveip.com/liveDb" // other environment-specific settings here } } }

    4.3.2 JNDI データソース

    h4. Referring to a JNDI DataSource


    Most Java EE containers supply DataSource instances via Java Naming and Directory Interface (JNDI). Grails supports the definition of JNDI data sources as follows:
    ほとんどのJavaEEコンテナはJava Naming and Directory Interface (JNDI)を通して、DataSourceインスタンスを提供しています。Grailsでは次のようにJNDIデータソースの定義をサポートしています。

    dataSource {
        jndiName = "java:comp/env/myDataSource"

    The format on the JNDI name may vary from container to container, but the way you define the DataSource in Grails remains the same.

    h4. Configuring a Development time JNDI resource


    The way in which you configure JNDI data sources at development time is plugin dependent. Using the Tomcat plugin you can define JNDI resources using the grails.naming.entries setting in grails-app/conf/Config.groovy:

    grails.naming.entries = [
        "bean/MyBeanFactory": [
            auth: "Container",
            type: "com.mycompany.MyBean",
            factory: "org.apache.naming.factory.BeanFactory",
            bar: "23"
        "jdbc/EmployeeDB": [
            type: "javax.sql.DataSource", //required
            auth: "Container", // optional
            description: "Data source for Foo", //optional
            driverClassName: "org.h2.Driver",
            url: "jdbc:h2:mem:database",
            username: "dbusername",
            password: "dbpassword",
            maxActive: "8",
            maxIdle: "4"
        "mail/session": [
            type: "javax.mail.Session,
            auth: "Container",
            "mail.smtp.host": "localhost"

    4.3.3 自動データベースマイグレーション

    The dbCreate property of the DataSource definition is important as it dictates what Grails should do at runtime with regards to automatically generating the database tables from GORM classes. The options are described in the DataSource section:
    • create
    • create-drop
    • update
    • validate
    • no value

    In development mode dbCreate is by default set to "create-drop", but at some point in development (and certainly once you go to production) you'll need to stop dropping and re-creating the database every time you start up your server.

    It's tempting to switch to update so you retain existing data and only update the schema when your code changes, but Hibernate's update support is very conservative. It won't make any changes that could result in data loss, and doesn't detect renamed columns or tables, so you'll be left with the old one and will also have the new one.

    Grails supports migrations via the Database Migration plugin which can be installed by declaring the plugin in grails-app/conf/BuildConfig.groovy:
    GrailsはDatabase Migration を介してマイグレーションをサポートしています。それはgrails-app/conf/BuildConfig.groovyに宣言することでプラグインとしてインストールすることができます。:

    grails.project.dependency.resolution = {
        plugins {
            runtime ':database-migration:1.3.1'

    The plugin uses Liquibase and and provides access to all of its functionality, and also has support for GORM (for example generating a change set by comparing your domain classes to a database).
    このプラグインはLiquibase を使用しており、Liquibaseすべての機能へのアクセスを提供しています。また、GORMのサポートも提供しています(例えばドメインクラスとデータベースを比較しチェンジセットを生成します)。

    4.3.4 Transaction-awareデータソースプロキシ

    The actual dataSource bean is wrapped in a transaction-aware proxy so you will be given the connection that's being used by the current transaction or Hibernate Session if one is active.

    If this were not the case, then retrieving a connection from the dataSource would be a new connection, and you wouldn't be able to see changes that haven't been committed yet (assuming you have a sensible transaction isolation setting, e.g. READ_COMMITTED or better).


    The "real" unproxied dataSource is still available to you if you need access to it; its bean name is dataSourceUnproxied.

    You can access this bean like any other Spring bean, i.e. using dependency injection:

    class MyService {

    def dataSourceUnproxied … }

    or by pulling it from the ApplicationContext:

    def dataSourceUnproxied = ctx.dataSourceUnproxied

    4.3.5 データベースコンソール

    The H2 database console is a convenient feature of H2 that provides a web-based interface to any database that you have a JDBC driver for, and it's very useful to view the database you're developing against. It's especially useful when running against an in-memory database.
    H2 database consoleはJDBCドライバを持つデータベースにWebベースのインタフェースを与えるH2の便利な機能であり、開発中のデータベースの表示に非常に便利です。インメモリデータベースに対して実行している場合には特に便利です。

    You can access the console by navigating to http://localhost:8080/appname/dbconsole in a browser. The URI can be configured using the grails.dbconsole.urlRoot attribute in Config.groovy and defaults to '/dbconsole'.

    The console is enabled by default in development mode and can be disabled or enabled in other environments by using the grails.dbconsole.enabled attribute in Config.groovy. For example you could enable the console in production using

    environments {
        production {
            grails.serverURL = "http://www.changeme.com"
            grails.dbconsole.enabled = true
            grails.dbconsole.urlRoot = '/admin/dbconsole'
        development {
            grails.serverURL = "http://localhost:8080/${appName}"
        test {
            grails.serverURL = "http://localhost:8080/${appName}"

    If you enable the console in production be sure to guard access to it using a trusted security framework.


    h4. Configuration


    By default the console is configured for an H2 database which will work with the default settings if you haven't configured an external database - you just need to change the JDBC URL to jdbc:h2:mem:devDB. If you've configured an external database (e.g. MySQL, Oracle, etc.) then you can use the Saved Settings dropdown to choose a settings template and fill in the url and username/password information from your DataSource.groovy.

    4.3.6 複数データソース

    By default all domain classes share a single DataSource and a single database, but you have the option to partition your domain classes into two or more DataSources.

    h4. Configuring Additional DataSources

    The default DataSource configuration in grails-app/conf/DataSource.groovy looks something like this:

    dataSource {
        pooled = true
        driverClassName = "org.h2.Driver"
        username = "sa"
        password = ""
    hibernate {
        cache.use_second_level_cache = true
        cache.use_query_cache = true
        cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'

    environments { development { dataSource { dbCreate = "create-drop" url = "jdbc:h2:mem:devDb" } } test { dataSource { dbCreate = "update" url = "jdbc:h2:mem:testDb" } } production { dataSource { dbCreate = "update" url = "jdbc:h2:prodDb" } } }

    This configures a single DataSource with the Spring bean named dataSource. To configure extra DataSources, add another dataSource block (at the top level, in an environment block, or both, just like the standard DataSource definition) with a custom name, separated by an underscore. For example, this configuration adds a second DataSource, using MySQL in the development environment and Oracle in production:

    environments {
        development {
            dataSource {
                dbCreate = "create-drop"
                url = "jdbc:h2:mem:devDb"
            dataSource_lookup {
                dialect = org.hibernate.dialect.MySQLInnoDBDialect
                driverClassName = 'com.mysql.jdbc.Driver'
                username = 'lookup'
                password = 'secret'
                url = 'jdbc:mysql://localhost/lookup'
                dbCreate = 'update'
        test {
            dataSource {
                dbCreate = "update"
                url = "jdbc:h2:mem:testDb"
        production {
            dataSource {
                dbCreate = "update"
                url = "jdbc:h2:prodDb"
            dataSource_lookup {
                dialect = org.hibernate.dialect.Oracle10gDialect
                driverClassName = 'oracle.jdbc.driver.OracleDriver'
                username = 'lookup'
                password = 'secret'
                url = 'jdbc:oracle:thin:@localhost:1521:lookup'
                dbCreate = 'update'

    You can use the same or different databases as long as they're supported by Hibernate.

    h4. Configuring Domain Classes


    If a domain class has no DataSource configuration, it defaults to the standard 'dataSource'. Set the datasource property in the mapping block to configure a non-default DataSource. For example, if you want to use the ZipCode domain to use the 'lookup' DataSource, configure it like this;
    ドメインクラスでDataSourceの設定をしていない場合、デフォルトで標準の'dataSource'が設定されます。デフォルトでないDataSourceを設定をするには、mappingブロック内でdatasourceプロパティを使用します。例えば、ZipCodeドメインで'lookup' DataSourceを利用したい場合、以下のように設定します。

    class ZipCode {

    String code

    static mapping = { datasource 'lookup' } }

    A domain class can also use two or more DataSources. Use the datasources property with a list of names to configure more than one, for example:

    class ZipCode {

    String code

    static mapping = { datasources(['lookup', 'auditing']) } }

    If a domain class uses the default DataSource and one or more others, use the special name 'DEFAULT' to indicate the default DataSource:

    class ZipCode {

    String code

    static mapping = { datasources(['lookup', 'DEFAULT']) } }

    If a domain class uses all configured DataSources use the special value 'ALL':

    class ZipCode {

    String code

    static mapping = { datasource 'ALL' } }

    h4. Namespaces and GORM Methods


    If a domain class uses more than one DataSource then you can use the namespace implied by each DataSource name to make GORM calls for a particular DataSource. For example, consider this class which uses two DataSources:

    class ZipCode {

    String code

    static mapping = { datasources(['lookup', 'auditing']) } }

    The first DataSource specified is the default when not using an explicit namespace, so in this case we default to 'lookup'. But you can call GORM methods on the 'auditing' DataSource with the DataSource name, for example:
    明示的に名前空間を使用しない場合、先頭のDataSourceがデフォルトとして使用されます。この場合デフォルトは'lookup'となります。また、以下のように'auditing' DataSource上でGORMメソッドを呼ぶことができます。

    def zipCode = ZipCode.auditing.get(42)

    As you can see, you add the DataSource to the method call in both the static case and the instance case.

    h4. Hibernate Mapped Domain Classes


    You can also partition annotated Java classes into separate datasources. Classes using the default datasource are registered in grails-app/conf/hibernate/hibernate.cfg.xml. To specify that an annotated class uses a non-default datasource, create a hibernate.cfg.xml file for that datasource with the file name prefixed with the datasource name.

    For example if the Book class is in the default datasource, you would register that in grails-app/conf/hibernate/hibernate.cfg.xml:

    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
              '-//Hibernate/Hibernate Configuration DTD 3.0//EN'
          <mapping class='org.example.Book'/>

    and if the Library class is in the "ds2" datasource, you would register that in grails-app/conf/hibernate/ds2_hibernate.cfg.xml:

    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
              '-//Hibernate/Hibernate Configuration DTD 3.0//EN'
          <mapping class='org.example.Library'/>

    The process is the same for classes mapped with hbm.xml files - just list them in the appropriate hibernate.cfg.xml file.

    h4. Services


    Like Domain classes, by default Services use the default DataSource and PlatformTransactionManager. To configure a Service to use a different DataSource, use the static datasource property, for example:

    class DataService {

    static datasource = 'lookup'

    void someMethod(...) { … } }

    A transactional service can only use a single DataSource, so be sure to only make changes for domain classes whose DataSource is the same as the Service.

    Note that the datasource specified in a service has no bearing on which datasources are used for domain classes; that's determined by their declared datasources in the domain classes themselves. It's used to declare which transaction manager to use.

    What you'll see is that if you have a Foo domain class in dataSource1 and a Bar domain class in dataSource2, and WahooService uses dataSource1, a service method that saves a new Foo and a new Bar will only be transactional for Foo since they share the datasource. The transaction won't affect the Bar instance. If you want both to be transactional you'd need to use two services and XA datasources for two-phase commit, e.g. with the Atomikos plugin.
    つまり、データソース1にFooドメインクラスを、データソース2にBarドメインクラスを持ち、WahooServiceがデータソース1を使うならば、FooとBarをnewするサービスのメソッドはデータソースを共有しているFooのためだけにトランザクション管理ができるということです。トランザクションはBarのインスタンスに影響を与えません。両方ともトランザクション管理をしたい場合は、2相コミットのために2つのサービスとXAデータソースを用いる必要があります。(例: Atomikosプラグイン)

    h4. XA and Two-phase Commit


    Grails has no native support for XA DataSources or two-phase commit, but the Atomikos plugin makes it easy. See the plugin documentation for the simple changes needed in your DataSource definitions to reconfigure them as XA DataSources.
    GrailsはネイティブでXA DataSource2相コミットに対応していませんが、Atomikosプラグインで簡単に行うことができます。DataSource定義をXA DataSourceとして再設定するのには簡単な変更が必要となるため、プラグインのドキュメントを参照してください。

    4.4 設定の外部化

    Some deployments require that configuration be sourced from more than one place and be changeable without requiring a rebuild of the application. In order to support deployment scenarios such as these the configuration can be externalized. To do so, point Grails at the locations of the configuration files that should be used by adding a grails.config.locations setting in Config.groovy, for example:

    grails.config.locations = [
        "file:${userHome}/.grails/${appName}-config.groovy" ]

    In the above example we're loading configuration files (both Java Properties files and ConfigSlurper configurations) from different places on the classpath and files located in USER_HOME.
    上記の例では、クラスパスやUSER_HOME内のファイルといった異なる場所から、設定ファイル(Javaのプロパティファイルや ConfigSlurper 設定ファイル)を読み込んでいます。

    It is also possible to load config by specifying a class that is a config script.

    grails.config.locations = [com.my.app.MyConfig]

    This can be useful in situations where the config is either coming from a plugin or some other part of your application. A typical use for this is re-using configuration provided by plugins across multiple applications.

    Ultimately all configuration files get merged into the config property of the GrailsApplication object and are hence obtainable from there.

    Values that have the same name as previously defined values will overwrite the existing values, and the pointed to configuration sources are loaded in the order in which they are defined.


    The configuration values contained in the locations described by the grails.config.locations property will override any values defined in your application Config.groovy file which may not be what you want. You may want to have a set of default values be be loaded that can be overridden in either your application's Config.groovy file or in a named config location. For this you can use the grails.config.defaults.locations property.

    This property supports the same values as the grails.config.locations property (i.e. paths to config scripts, property files or classes), but the config described by grails.config.defaults.locations will be loaded before all other values and can therefore be overridden. Some plugins use this mechanism to supply one or more sets of default configuration that you can choose to include in your application config.

    Grails also supports the concept of property place holders and property override configurers as defined in Spring For more information on these see the section on Grails and Spring
    GrailsはSpringで定義されているようなプレースホルダや設定のオーバライドといったプロパティの概念をサポートしています。より詳しい情報はGrails and Springの章を参照してください。

    4.5 バージョニング

    h4. Versioning Basics


    Grails has built in support for application versioning. The version of the application is set to 0.1 when you first create an application with the create-app command. The version is stored in the application meta data file application.properties in the root of the project.

    To change the version of your application you can edit the file manually, or run the set-version command:

    grails set-version 0.2

    The version is used in various commands including the war command which will append the application version to the end of the created WAR file.

    h4. Detecting Versions at Runtime


    You can detect the application version using Grails' support for application metadata using the GrailsApplication class. For example within controllers there is an implicit grailsApplication variable that can be used:

    def version = grailsApplication.metadata['app.version']

    You can retrieve the the version of Grails that is running with:

    def grailsVersion = grailsApplication.metadata['app.grails.version']

    or the GrailsUtil class:

    import grails.util.GrailsUtil
    def grailsVersion = GrailsUtil.grailsVersion

    4.6 プロジェクト・ドキュメント

    Since Grails 1.2, the documentation engine that powers the creation of this documentation has been available for your own Grails projects.

    The documentation engine uses a variation on the Textile syntax to automatically create project documentation with smart linking, formatting etc.

    h4. Creating project documentation


    To use the engine you need to follow a few conventions. First, you need to create a src/docs/guide directory where your documentation source files will go. Then, you need to create the source docs themselves. Each chapter should have its own gdoc file as should all numbered sub-sections. You will end up with something like:

    + src/docs/guide/introduction.gdoc
    + src/docs/guide/introduction/changes.gdoc
    + src/docs/guide/gettingStarted.gdoc
    + src/docs/guide/configuration.gdoc
    + src/docs/guide/configuration/build.gdoc
    + src/docs/guide/configuration/build/controllers.gdoc

    Note that you can have all your gdoc files in the top-level directory if you want, but you can also put sub-sections in sub-directories named after the parent section - as the above example shows.

    Once you have your source files, you still need to tell the documentation engine what the structure of your user guide is going to be. To do that, you add a src/docs/guide/toc.yml file that contains the structure and titles for each section. This file is in YAML format and basically represents the structure of the user guide in tree form. For example, the above files could be represented as:

      title: Introduction
      changes: Change Log
    gettingStarted: Getting Started
      title: Configuration
        title: Build Config
        controllers: Specifying Controllers

    The format is pretty straightforward. Any section that has sub-sections is represented with the corresponding filename (minus the .gdoc extension) followed by a colon. The next line should contain title: plus the title of the section as seen by the end user. Every sub-section then has its own line after the title. Leaf nodes, i.e. those without any sub-sections, declare their title on the same line as the section name but after the colon.

    That's it. You can easily add, remove, and move sections within the toc.yml to restructure the generated user guide. You should also make sure that all section names, i.e. the gdoc filenames, should be unique since they are used for creating internal links and for the HTML filenames. Don't worry though, the documentation engine will warn you of duplicate section names.

    h4. Creating reference items


    Reference items appear in the Quick Reference section of the documentation. Each reference item belongs to a category and a category is a directory located in the src/docs/ref directory. For example, suppose you have defined a new controller method called renderPDF. That belongs to the Controllers category so you would create a gdoc text file at the following location:

    + src/docs/ref/Controllers/renderPDF.gdoc

    h4. Configuring Output Properties


    There are various properties you can set within your grails-app/conf/Config.groovy file that customize the output of the documentation such as:

    • grails.doc.title - The title of the documentation
    • grails.doc.subtitle - The subtitle of the documentation
    • grails.doc.authors - The authors of the documentation
    • grails.doc.license - The license of the software
    • grails.doc.copyright - The copyright message to display
    • grails.doc.footer - The footer to use

    • grails.doc.title - ドキュメントのタイトル
    • grails.doc.subtitle - ドキュメントのサブタイトル
    • grails.doc.authors - ドキュメントの著者
    • grails.doc.license - ソフトウェアライセンス
    • grails.doc.copyright - copyrightメッセージの表示
    • grails.doc.footer - 使用するフッター

    Other properties such as the version are pulled from your project itself. If a title is not specified, the application name is used.

    You can also customise the look of the documentation and provide images by setting a few other options:

    • grails.doc.css - The location of a directory containing custom CSS files (type java.io.File)
    • grails.doc.js - The location of a directory containing custom JavaScript files (type java.io.File)
    • grails.doc.style - The location of a directory containing custom HTML templates for the guide (type java.io.File)
    • grails.doc.images - The location of a directory containing image files for use in the style templates and within the documentation pages themselves (type java.io.File)

    • grails.doc.css - カスタマイズしたCSSファイルを含むディレクトリ場所(java.io.Fileクラスの型)
    • grails.doc.js - カスタマイズしたJavaScriptファイルを含むディレクトリ場所(java.io.Fileクラスの型)
    • grails.doc.style - ガイド用にカスタマイズしたHTMLテンプレートを含むディレクトリ場所(java.io.Fileクラスの型)
    • grails.doc.images - スタイルテンプレートやドキュメントページ自身で使用する画像ファイルを含むディレクトリ場所(java.io.Fileの型)

    One of the simplest ways to customise the look of the generated guide is to provide a value for grails.doc.css and then put a custom.css file in the corresponding directory. Grails will automatically include this CSS file in the guide. You can also place a custom-pdf.css file in that directory. This allows you to override the styles for the PDF version of the guide.

    h4. Generating Documentation


    Once you have created some documentation (refer to the syntax guide in the next chapter) you can generate an HTML version of the documentation using the command:

    grails doc

    This command will output an docs/manual/index.html which can be opened in a browser to view your documentation.

    h4. Documentation Syntax


    As mentioned the syntax is largely similar to Textile or Confluence style wiki markup. The following sections walk you through the syntax basics.

    h5. Basic Formatting

    Monospace: monospace
    等幅フォント: monospace

    Italic: italic
    イタリック体: italic

    Bold: bold
    太字: bold



    You can also link to internal images like so:


    This will link to an image stored locally within your project. There is currently no default location for doc images, but you can specify one with the grails.doc.images setting in Config.groovy like so:

    grails.doc.images = new File("src/docs/images")

    In this example, you would put the my_diagram.png file in the directory 'src/docs/images/someFolder'.

    h5. Linking

    There are several ways to create links with the documentation generator. A basic external link can either be defined using confluence or textile style markup:




    For links to other sections inside the user guide you can use the guide: prefix with the name of the section you want to link to:


    The section name comes from the corresponding gdoc filename. The documentation engine will warn you if any links to sections in your guide break.

    To link to reference items you can use a special syntax:


    In this case the category of the reference item is on the left hand side of the | and the name of the reference item on the right.

    Finally, to link to external APIs you can use the api: prefix. For example:


    The documentation engine will automatically create the appropriate javadoc link in this case. To add additional APIs to the engine you can configure them in grails-app/conf/Config.groovy. For example:


    The above example configures classes within the org.hibernate package to link to the Hibernate website's API docs.

    h5. Lists and Headings

    Headings can be created by specifying the letter 'h' followed by a number and then a dot:


    Unordered lists are defined with the use of the * character:

    * item 1
    ** subitem 1
    ** subitem 2
    * item 2

    Numbered lists can be defined with the # character:

    # item 1

    Tables can be created using the table macro:


     *Name* | *Number*
     Albert | 46
     Wilma | 1348
     James | 12

    h5. Code and Notes

    You can define code blocks with the code macro:

    class Book {
        String title

    class Book {
        String title

    The example above provides syntax highlighting for Java and Groovy code, but you can also highlight XML markup:



    There are also a couple of macros for displaying notes and warnings:


    This is a note!

    This is a note!


    This is a warning!

    This is a warning!

    4.7 依存性解決

    Grails features a dependency resolution DSL that lets you control how plugins and JAR dependencies are resolved.

    You can choose to use Aether (since Grails 2.3) or Apache Ivy as the dependency resolution engine. Aether is the dependency resolution library used by the Maven build tool, so if you are looking for Maven-like behavior then Aether is the better choise. Ivy allows more flexibility if you wish to resolve jars from flat file systems or none HTTP repositories. Aether is the default dependency resolution engine for Grails applications since Grails 2.3.
    依存関係解決エンジンとして、Aether(Grails2.3以降)あるいはApache Ivyのどちらかを選択できます。Aetherは、Mavenビルド・ツール内で使用されている依存関係解決ライブラリであり、Mavenのような振る舞いを期待しているなら、Aetherを選択すべきです。Ivyは、単層ファイルシステムまたはHTTP通信を行わないリポジトリからjarファイルを解決したい場合には、より柔軟性が高いです。Grails 2.3以降においては、AetherがGrailsアプリケーションのデフォルトの依存関係解決エンジンです。

    To configure which dependency resolution engine to use you can specify the grails.project.dependency.resolver setting in grails-app/conf/BuildConfig.groovy. The default setting is shown below:

    grails.project.dependency.resolver = "maven" // or ivy

    You can then specify a grails.project.dependency.resolution property inside the grails-app/conf/BuildConfig.groovy file that configures how dependencies are resolved:

    grails.project.dependency.resolution = {
       // config here

    The default configuration looks like the following:

    grails.project.class.dir = "target/classes"
    grails.project.test.class.dir = "target/test-classes"
    grails.project.test.reports.dir = "target/test-reports"
    //grails.project.war.file = "target/${appName}-${appVersion}.war"

    grails.project.dependency.resolution = { // inherit Grails' default dependencies inherits("global") { // uncomment to disable ehcache // excludes 'ehcache' } log "warn" repositories { grailsPlugins() grailsHome() grailsCentral() mavenCentral() mavenLocal()

    // uncomment these to enable remote dependency resolution // from public Maven repositories //mavenRepo "http://snapshots.repository.codehaus.org" //mavenRepo "http://repository.codehaus.org" //mavenRepo "http://download.java.net/maven/2/" //mavenRepo "http://repository.jboss.com/maven2/" } dependencies { // specify dependencies here under either 'build', 'compile', // 'runtime', 'test' or 'provided' scopes eg.

    // runtime 'mysql:mysql-connector-java:5.1.16' build "org.grails:grails-plugin-tomcat:$grailsVersion" runtime "org.grails:grails-plugin-hibernate:$grailsVersion" }

    plugins {

    compile ":jquery:1.8.3" compile ":resources:1.1.6"

    build ":tomcat:$grailsVersion" } }

    The details of the above will be explained in the next few sections.

    4.7.1 設定と依存

    Grails features five dependency resolution configurations (or 'scopes'):

    * build: Dependencies for the build system only
    • build: ビルドシステムのためだけの依存関係

    * compile: Dependencies for the compile step
    • compile: コンパイルのための依存関係

    * runtime: Dependencies needed at runtime but not for compilation (see above)
    • runtime: 実行時には必要だが、コンパイル時には不必要な依存関係(上記参照)

    * test: Dependencies needed for testing but not at runtime (see above)
    • test: テスト時には必要だが、実行時には不必要な依存関係(上記参照)

    * provided: Dependencies needed at development time, but not during WAR deployment
    • provided: 開発時には必要だが、WARファイルのデプロイ時には不必要な依存関係

    Within the dependencies block you can specify a dependency that falls into one of these configurations by calling the equivalent method. For example if your application requires the MySQL driver to function at runtime you can specify that like this:

    runtime 'com.mysql:mysql-connector-java:5.1.16'

    This uses the string syntax: group:name:version.

    If you are using Aether as the dependency resolution library, the Maven pattern of:


    You can also use a Map-based syntax:

    runtime group: 'com.mysql',
            name: 'mysql-connector-java',
            version: '5.1.16'

    Possible settings to the map syntax are:

    * group - The group / organization (or groupId in Maven terminology)
    • group - グループ/組織(Mavenの用語ではgroupId)

    * name - The dependency name (or artifactId in Maven terminology)
    • name - 依存関係名 (Mavenの用語ではartifactId)

    * version - The version of the dependency
    • version - 依存関係のバージョン

    * extension (Aether only) - The file extension of the dependency
    • extension (Aetherのみ) - 依存関係のファイル拡張子

    * classifier - The dependency classifier
    • classifier - 依存関係の分類

    * branch (Ivy only) - The branch of the dependency
    • branch(Ivyのみ) - 依存関係のブランチ

    * transitive (Ivy only) - Whether the dependency has transitive dependencies
    • transitive (Ivyのみ) - 推移的依存関係の有無

    As you can see from the list above some dependency configuration settings work only in Aether and some only in Ivy.

    Multiple dependencies can be specified by passing multiple arguments:

    runtime 'com.mysql:mysql-connector-java:5.1.16',

    // Or

    runtime( [group:'com.mysql', name:'mysql-connector-java', version:'5.1.16'], [group:'net.sf.ehcache', name:'ehcache', version:'1.6.1'] )

    h3. Disabling transitive dependency resolution


    By default, Grails will not only get the JARs and plugins that you declare, but it will also get their transitive dependencies. This is usually what you want, but there are occasions where you want a dependency without all its baggage. In such cases, you can disable transitive dependency resolution on a case-by-case basis:

            'net.sf.ehcache:ehcache:1.6.1') {
        transitive = false

    // Or runtime group:'com.mysql', name:'mysql-connector-java', version:'5.1.16', transitive:false

    Disabling transitive dependency resolution only works with the Ivy dependency manager. Aether does not support disabling of transitive resolution, instead explicit exclusions are required (see below).


    h3. Excluding specific transitive dependencies


    A far more common scenario is where you want the transitive dependencies, but some of them cause issues with your own dependencies or are unnecessary. For example, many Apache projects have 'commons-logging' as a transitive dependency, but it shouldn't be included in a Grails project (we use SLF4J). That's where the excludes option comes in:

            'net.sf.ehcache:ehcache:1.6.1') {
        excludes "xml-apis", "commons-logging"

    // Or runtime(group:'com.mysql', name:'mysql-connector-java', version:'5.1.16') { excludes([ group: 'xml-apis', name: 'xml-apis'], [ group: 'org.apache.httpcomponents' ], [ name: 'commons-logging' ])

    As you can see, you can either exclude dependencies by their artifact ID (also known as a module name) or any combination of group and artifact IDs (if you use the Map notation). You may also come across exclude as well, but that can only accept a single string or Map:

            'net.sf.ehcache:ehcache:1.6.1') {
        exclude "xml-apis"

    h3. Using Ivy module configurations


    Using the Ivy dependency manager (Aether not supported), if you use Ivy module configurations and wish to depend on a specific configuration of a module, you can use the dependencyConfiguration method to specify the configuration to use.

    provided("my.org:web-service:1.0") {
        dependencyConfiguration "api"

    If the dependency configuration is not explicitly set, the configuration named "default" will be used (which is also the correct value for dependencies coming from Maven style repositories).

    h3. Where are the JARs?


    With all these declarative dependencies, you may wonder where all the JARs end up. They have to go somewhere after all. By default Grails puts them into a directory, called the dependency cache, that resides on your local file system at user.home/.grails/ivy-cache or user.home/.m2/repository when using Aether. You can change this either via the settings.groovy file:

    grails.dependency.cache.dir = "${userHome}/.my-dependency-cache"

    or in the dependency DSL:

    grails.project.dependency.resolution = {
        cacheDir "target/ivy-cache"

    The settings.groovy option applies to all projects, so it's the preferred approach.

    4.7.2 依存管理リポジトリ

    h4. Remote Repositories


    Initially your BuildConfig.groovy does not use any remote public Maven repositories. There is a default grailsHome() repository that will locate the JAR files Grails needs from your Grails installation. To use a public repository, specify it in the repositories block:

    repositories {

    In this case the default public Maven repository is specified.

    You can also specify a specific Maven repository to use by URL:

    repositories {
        mavenRepo "http://repository.codehaus.org"

    and even give it a name:

    repositories {
        mavenRepo name: "Codehaus", root: "http://repository.codehaus.org"

    so that you can easily identify it in logs.

    h4. Controlling Repositories Inherited from Plugins


    A plugin you have installed may define a reference to a remote repository just as an application can. By default your application will inherit this repository definition when you install the plugin.

    If you do not wish to inherit repository definitions from plugins then you can disable repository inheritance:

    repositories {
        inherit false

    In this case your application will not inherit any repository definitions from plugins and it is down to you to provide appropriate (possibly internal) repository definitions.

    h4. Offline Mode


    There are times when it is not desirable to connect to any remote repositories (whilst working on the train for example!). In this case you can use the offline flag to execute Grails commands and Grails will not connect to any remote repositories:

    grails --offline run-app

    Note that this command will fail if you do not have the necessary dependencies in your local Ivy cache


    You can also globally configure offline mode by setting grails.offline.mode to true in ~/.grails/settings.groovy or in your project's BuildConfig.groovy file:


    h4. Local Resolvers


    If you do not wish to use a public Maven repository you can specify a flat file repository:

    repositories {
        flatDir name:'myRepo', dirs:'/path/to/repo'

    Aether does not support the flatDir resolver or any custom file system resolvers. The above feature works only if you are using the Ivy dependency manager.


    To specify your local Maven cache (~/.m2/repository) as a repository:

    repositories {

    h4. Custom Resolvers


    If you are using the Ivy dependency manager (Aether does not support custom resolvers), then you can explicitly specify an Ivy resolver:

     * Configure our resolver.
    def libResolver = new org.apache.ivy.plugins.resolver.URLResolver()
    ['libraries', 'builds'].each {

    libResolver.addArtifactPattern( "http://my.repository/${it}/" + "[organisation]/[module]/[revision]/[type]s/[artifact].[ext]")

    libResolver.addIvyPattern( "http://my.repository/${it}/" + "[organisation]/[module]/[revision]/[type]s/[artifact].[ext]") }

    libResolver.name = "my-repository" libResolver.settings = ivySettings

    resolver libResolver

    It's also possible to pull dependencies from a repository using SSH. Ivy comes with a dedicated resolver that you can configure and include in your project like so:

    import org.apache.ivy.plugins.resolver.SshResolver
    repositories {

    def sshResolver = new SshResolver( name: "myRepo", user: "username", host: "dev.x.com", keyFile: new File("/home/username/.ssh/id_rsa"), m2compatible: true)

    sshResolver.addArtifactPattern( "/home/grails/repo/[organisation]/[artifact]/" + "[revision]/[artifact]-[revision].[ext]")

    sshResolver.latestStrategy = new org.apache.ivy.plugins.latest.LatestTimeStrategy()

    sshResolver.changingPattern = ".*SNAPSHOT"


    resolver sshResolver }

    Download the JSch JAR and add it to Grails' classpath to use the SSH resolver. You can do this by passing the path in the Grails command line:
    SSHリゾルバを使用するために、JSch JARをダウンロードしGrailsのクラスパスに追加します。Grailsのコマンドラインでパスを通すことによってこれを実行出来ます:

    grails -classpath /path/to/jsch compile|run-app|etc.

    You can also add its path to the CLASSPATH environment variable but be aware this it affects many Java applications. An alternative on Unix is to create an alias for grails -classpath ... so that you don't have to type the extra arguments each time.
    また、CLASSPATH環境変数にパスを通すことでも追加できますが、多くのJavaアプリケーションに影響を与えることに注意する必要があります。Unix上で引数を毎回入力する面倒を避けるには、grails -classpath...コマンドのエイリアスを作成するのが良いでしょう。

    h4. Authentication


    If your repository requires authentication you can configure this using a credentials block:

    credentials {
        realm = ".."
        host = "localhost"
        username = "myuser"
        password = "mypass"

    This can be placed in your USER_HOME/.grails/settings.groovy file using the grails.project.ivy.authentication setting:

    grails.project.ivy.authentication = {
        credentials {
            realm = ".."
            host = "localhost"
            username = "myuser"
            password = "mypass"

    4.7.3 依存解決デバッグ

    If you are having trouble getting a dependency to resolve you can enable more verbose debugging from the underlying engine using the log method:

    // log level of the Aether or Ivy resolver, either 'error', 'warn',
    // 'info', 'debug' or 'verbose'
    log "warn"

    A common issue is that the checksums for a dependency don't match the associated JAR file, and so Ivy rejects the dependency. This helps ensure that the dependencies are valid. But for a variety of reasons some dependencies simply don't have valid checksums in the repositories, even if they are valid JARs. To get round this, you can disable Ivy's dependency checks like so:

    grails.project.dependency.resolution = {
        log "warn"
        checksums false

    This is a global setting, so only use it if you have to.

    4.7.4 依存の受け継ぎ

    By default every Grails application inherits several framework dependencies. This is done through the line:

    inherits "global"

    Inside the BuildConfig.groovy file. To exclude specific inherited dependencies you use the excludes method:

    inherits("global") {
        excludes "oscache", "ehcache"

    4.7.5 基本依存管理の提供

    Most Grails applications have runtime dependencies on several jar files that are provided by the Grails framework. These include libraries like Spring, Sitemesh, Hibernate etc. When a war file is created, all of these dependencies will be included in it. But, an application may choose to exclude these jar files from the war. This is useful when the jar files will be provided by the container, as would normally be the case if multiple Grails applications are deployed to the same container.

    The dependency resolution DSL provides a mechanism to express that all of the default dependencies will be provided by the container. This is done by invoking the defaultDependenciesProvided method and passing true as an argument:

    grails.project.dependency.resolution = {

    defaultDependenciesProvided true // all of the default dependencies will // be "provided" by the container

    inherits "global" // inherit Grails' default dependencies

    repositories { grailsHome() … } dependencies { … } }

    grails.project.dependency.resolution = {

    defaultDependenciesProvided true // 全てのデフォルトの依存関係は // コンテナによって提供される

    inherits "global" // Grailsのデフォルト依存関係を継承する

    repositories { grailsHome() … } dependencies { … } }

    defaultDependenciesProvided must come before inherits, otherwise the Grails dependencies will be included in the war.


    4.7.6 スナップショットと他の変化する依存関係

    h4. Configuration Changing dependencies


    Typically, dependencies are constant. That is, for a given combination of group, name and version the jar (or plugin) that it refers to will never change. The Grails dependency management system uses this fact to cache dependencies in order to avoid having to download them from the source repository each time. Sometimes this is not desirable. For example, many developers use the convention of a snapshot (i.e. a dependency with a version number ending in “-SNAPSHOT”) that can change from time to time while still retaining the same version number. We call this a "changing dependency".

    Whenever you have a changing dependency, Grails will always check the remote repository for a new version. More specifically, when a changing dependency is encountered during dependency resolution its last modified timestamp in the local cache is compared against the last modified timestamp in the dependency repositories. If the version on the remote server is deemed to be newer than the version in the local cache, the new version will be downloaded and used.

    Be sure to read the next section on “Dependency Resolution Caching” in addition to this one as it affects changing dependencies.


    All dependencies (jars and plugins) with a version number ending in -SNAPSHOT are implicitly considered to be changing by Grails. You can also explicitly specify that a dependency is changing by setting the changing flag in the dependency DSL (This is only required for Ivy, Aether does not support the 'changing' flag and treats dependencies that end with -SNAPSHOT as changing):

    runtime ('org.my:lib:1.2.3') {
        changing = true

    Aether and SNAPSHOT dependencies


    The semantics for handling snapshots when using Aether in Grails are the same as those when using the Maven build tool. The default snapshot check policy is to check once a day for a new version of the dependency. This means that if a new snapshot is published during the day to a remote repository you may not see that change unless you manually clear out your local snapshot.
    Grails内でAetherを使用した場合、スナップショットを処理するためのセマンティクスは、Mavenを使用した場合と同じです。 デフォルトのスナップショットのチェックポリシーでは、1日に1回、依存関係の新しいバージョンをチェックします。 これはその日リモートリポジトリに公開された新たなスナップショットが、手動でロカールリポジトリのスナップショットをクリアしない限り、変更を検知できない場合があるということです。

    If you wish to change the snapshot update policy you can do so by configuring an updatePolicy for the repository where the snapshot was resolved from, for example:
    もし、スナップショットのアップデートポリシーを変更したい場合は、スナップショットの依存を解決するリポジトリでupdatePolicyを設定します。 例えば以下のようにします:

    repositories {
        mavenCentral {
            updatePolicy "interval:1"

    The above example configures an update policy that checks once a minute for changes. Note that that an updatePolicy like the above will seriously impact performance of dependency resolution. The possibly configuration values for updatePolicy are as follows:
    上記の例では、1分に1回チェックをするアップデートポリシーを設定しています。 上記のupdatePolicyのように、この設定は依存関係解決のパフォーマンスに影響を与えることに注意してください。 updatePolicyに設定が可能な値は以下のとおりです:

    • never - Never check for new snapshots
    • always - Always check for new snapshots
    • daily - Check once a day for new snapshots (the default)
    • interval:x - Check once every x minutes for new snapshots

    • never - 新しいスナップショットをチェックしない
    • always - 常に新しいスナップショットをチェックする
    • daily - 1日に1回新しいスナップショットをチェックする (デフォルト)
    • interval:x - x分ごとに1回新しいスナップショットをチェックする

    h4. Ivy and Changing dependencies


    For those used to Maven snapshot handling, if you use Aether dependency management you can expect the same semantics as Maven. If you choose to use Ivy there is a caveat to the support for changing dependencies that you should be aware of. Ivy will stop looking for newer versions of a dependency once it finds a remote repository that has the dependency.

    Consider the following setup:

    grails.project.dependency.resolution = {
        repositories {
            mavenRepo "http://my.org/repo"
        dependencies {
            compile "myorg:mylib:1.0-SNAPSHOT"

    In this example we are using the local maven repository and a remote network maven repository. Assuming that the local OI dependency and the local Maven cache do not contain the dependency but the remote repository does, when we perform dependency resolution the following actions will occur:

    * maven local repository is searched, dependency not found
    • Mavenのローカルリポジトリが検索されますが、依存関係は見つかりません。

    * maven network repository is searched, dependency is downloaded to the cache and used
    • Mavenのネットワークリポジトリが検索され、依存関係をキャッシュへダウンロードして使用します。

    Note that the repositories are checked in the order they are defined in the BuildConfig.groovy file.

    If we perform dependency resolution again without the dependency changing on the remote server, the following will happen:

    * maven local repository is searched, dependency not found
    • Mavenのローカルリポジトリが検索されますが、依存関係は見つかりません。

    * maven network repository is searched, dependency is found to be the same “age” as the version in the cache so will not be updated (i.e. downloaded)
    • Mavenのネットワークリポジトリが検索され依存関係が見つかりますが、キャッシュ内のバージョンと同じ最終更新日時のため更新(すなわちダウンロード)はされません。

    Later on, a new version of mylib 1.0-SNAPSHOT is published changing the version on the server. The next time we perform dependency resolution, the following will happen:
    その後、mylib 1.0-SNAPSHOTの新しいバージョンが公開され、サーバ上のファイルが更新されたとします。この状況で依存関係の解決を実行した場合、以下の処理が行われます。

    * maven local repository is searched, dependency not found
    • Mavenのローカルリポジトリが検索されますが、依存関係は見つかりません。

    * maven network repository is searched, dependency is found to newer than version in the cache so will be updated (i.e. downloaded to the cache)
    • Mavenのネットワークリポジトリが検索され、キャッシュ内のバージョンよりも新しい依存関係が見つかり、更新(つまり、キャッシュにダウンロード)されます。

    So far everything is working well.

    Now we want to test some local changes to the mylib library. To do this we build it locally and install it to the local Maven cache (how doesn't particularly matter). The next time we perform a dependency resolution, the following will occur:

    * maven local repository is searched, dependency is found to newer than version in the cache so will be updated (i.e. downloaded to the cache)
    * maven network repository is NOT searched as we've already found the dependency

    This is what we wanted to occur.

    Later on, a new version of mylib 1.0-SNAPSHOT is published changing the version on the server. The next time we perform dependency resolution, the following will happen:
    その後、mylib 1.0-SNAPSHOTの新しいバージョンが公開され、サーバ上のファイルが更新されたとします。この状況で依存関係の解決を実行した場合、以下の処理が行われます。

    * maven local repository is searched, dependency is found to be the same “age” as the version in the cache so will not be updated (i.e. downloaded)
    • Mavenのローカルリポジトリが検索され、キャッシュ内バージョンと同じ”年齢”の依存関係が見つかりますが、更新(すなわちダウンロード)はされません。

    * maven network repository is NOT searched as we've already found the dependency
    • すでに依存関係を発見したため、Mavenのネットワークリポジトリは検索されません。

    This is likely to not be the desired outcome. We are now out of sync with the latest published snapshot and will continue to keep using the version from the local maven repository.

    The rule to remember is this: when resolving a dependency, Ivy will stop searching as soon as it finds a repository that has the dependency at the specified version number. It will not continue searching all repositories trying to find a more recently modified instance.

    To remedy this situation (i.e. build against the newer version of mylib 1.0-SNAPSHOT in the remote repository), you can either:
    この状況を改善するために(すなわちリモートリポジトリ内の、より新しいバージョンのmylib 1.0-SNAPSHOTをビルドするために)、次のいずれかを実行できます。

    * Delete the version from the local maven repository, or
    • Mavenのローカルリポジトリからバージョンを削除する

    * Reorder the repositories in the BuildConfig.groovy file
    • BuildConfig.groovyファイル内のリポジトリの順序を変更する

    Where possible, prefer deleting the version from the local maven repository. In general, when you have finished building against a locally built SNAPSHOT always try to clear it from the local maven repository.

    This changing dependency behaviour is an unmodifiable characteristic of the underlying dependency management system Apache Ivy. It is currently not possible to have Ivy search all repositories to look for newer versions (in terms of modification date) of the same dependency (i.e. the same combination of group, name and version). If you want this behavior consider switching to Aether as the dependency manager.

    この変化する依存関係の挙動は、Grailsの依存関係管理システムの基礎となっているApache Ivyの変更不可能な特性です。現在のところIvyは、すべてのリポジトリを検索し、同じ依存関係(すなわち等しいグループ名前バージョンの組み合わせ)の中から(修正日付の面で)より新しいバージョンのものを探すことはできません。

    4.7.7 依存管理レポート

    As mentioned in the previous section a Grails application consists of dependencies inherited from the framework, the plugins installed and the application dependencies itself.

    To obtain a report of an application's dependencies you can run the dependency-report command:

    grails dependency-report

    By default this will generate reports in the target/dependency-report directory. You can specify which configuration (scope) you want a report for by passing an argument containing the configuration name:

    grails dependency-report runtime

    As of Grails 2.3 the dependency-report command will also output to the console a graph of the dependencies of an application. Example output it shown below:

    compile - Dependencies placed on the classpath for compilation (total: 73)
    +--- org.codehaus.groovy:groovy-all:2.0.6
    +--- org.grails:grails-plugin-codecs:2.3.0
    |    --- org.grails:grails-web:2.3.0
    |         --- commons-fileupload:commons-fileupload:1.2.2
    |         --- xpp3:xpp3_min:1.1.4c
    |         --- commons-el:commons-el:1.0
    |         --- opensymphony:sitemesh:2.4
    |         --- org.springframework:spring-webmvc:3.1.2.RELEASE
    |    --- commons-codec:commons-codec:1.5
    |    --- org.slf4j:slf4j-api:1.7.2
    +--- org.grails:grails-plugin-controllers:2.3.0
    |    --- commons-beanutils:commons-beanutils:1.8.3
    |    --- org.grails:grails-core:2.3.0

    4.7.8 プラグインJAR依存

    h4. Specifying Plugin JAR dependencies


    The way in which you specify dependencies for a plugin is identical to how you specify dependencies in an application. When a plugin is installed into an application the application automatically inherits the dependencies of the plugin.

    To define a dependency that is resolved for use with the plugin but not exported to the application then you can set the export property of the dependency:
    compile('org.spockframework:spock-core:0.5-groovy-1.8') {
        export = false

    In this case the Spock dependency will be available only to the plugin and not resolved as an application dependency. Alternatively, if you're using the Map syntax:

    compile group: 'org.spockframework', name: 'spock-core',
         version: '0.5-groovy-1.8', export: false

    You can use exported = false instead of export = false, but we recommend the latter because it's consistent with the Map argument.


    h4. Overriding Plugin JAR Dependencies in Your Application


    If a plugin is using a JAR which conflicts with another plugin, or an application dependency then you can override how a plugin resolves its dependencies inside an application using exclusions. For example:

    plugins {
        compile(":hibernate:$grailsVersion") {
            excludes "javassist"

    dependencies { runtime "javassist:javassist:3.4.GA" }

    In this case the application explicitly declares a dependency on the "hibernate" plugin and specifies an exclusion using the excludes method, effectively excluding the javassist library as a dependency.

    4.7.9 Maven統合

    When using the Grails Maven plugin with the Maven build tool, Grails' dependency resolution mechanics are disabled as it is assumed that you will manage dependencies with Maven's pom.xml file.
    Grails Maven pluginでMavenビルドツールを使用している場合は、Mavanのpom.xmlファイルで依存関係の解決が行なわれると判断し、Grailsでの依存関係解決機能は無効化されます

    However, if you would like to continue using Grails regular commands like run-app, test-app and so on then you can tell Grails' command line to load dependencies from the Maven pom.xml file instead.

    To do so simply add the following line to your BuildConfig.groovy:

    grails.project.dependency.resolution = {
        pom true

    The line pom true tells Grails to parse Maven's pom.xml and load dependencies from there.
    pom true行は、Mavenのpom.xmlファイルの構文解析を行いそこから依存関係をロードする、ということをGrailsに通達します。

    4.7.10 Mavenリポジトリへのデプロイ

    If you use Maven to build your Grails project, you can use the standard Maven targets mvn install and mvn deploy.
    GrailsプロジェクトのビルドにMavenを使用する場合は、標準のMavenのターゲットであるmvn installおよびmvn deployを使用できます。
    If not, you can deploy a Grails project or plugin to a Maven repository using the release plugin.

    The plugin provides the ability to publish Grails projects and plugins to local and remote Maven repositories. There are two key additional targets added by the plugin:

    maven-install* - Installs a Grails project or plugin into your local Maven cache
    • maven-install - MavenのローカルキャッシュにGrailsプロジェクトやプラグインをインストールします。

    maven-deploy* - Deploys a Grails project or plugin to a remote Maven repository
    • maven-deploy - MavenのリモートリポジトリにGrailsプロジェクトやプラグインをデプロイします。

    By default this plugin will automatically generate a valid pom.xml for you unless a pom.xml is already present in the root of the project, in which case this pom.xml file will be used.

    h4. maven-install


    The maven-install command will install the Grails project or plugin artifact into your local Maven cache:

    grails maven-install

    In the case of plugins, the plugin zip file will be installed, whilst for application the application WAR file will be installed.

    h4. maven-deploy


    The maven-deploy command will deploy a Grails project or plugin into a remote Maven repository:

    grails maven-deploy

    It is assumed that you have specified the necessary <distributionManagement> configuration within a pom.xml or that you specify the id of the remote repository to deploy to:

    grails maven-deploy --repository=myRepo

    The repository argument specifies the 'id' for the repository. Configure the details of the repository specified by this 'id' within your grails-app/conf/BuildConfig.groovy file or in your $USER_HOME/.grails/settings.groovy file:

    grails.project.dependency.distribution = {
        localRepository = "/path/to/my/local"
        remoteRepository(id: "myRepo", url: "http://myserver/path/to/repo")

    The syntax for configuring remote repositories matches the syntax from the remoteRepository element in the Ant Maven tasks. For example the following XML:

    <remoteRepository id="myRepo" url="scp://localhost/www/repository">
        <authentication username="..." privateKey="${user.home}/.ssh/id_dsa"/>

    Can be expressed as:

    remoteRepository(id: "myRepo", url: "scp://localhost/www/repository") {
        authentication username: "...", privateKey: "${userHome}/.ssh/id_dsa"

    By default the plugin will try to detect the protocol to use from the URL of the repository (ie "http" from "http://.." etc.), however to specify a different protocol you can do:

    grails maven-deploy --repository=myRepo --protocol=webdav

    The available protocols are:
    • http
    • scp
    • scpexe
    • ftp
    • webdav

    h4. Groups, Artifacts and Versions


    Maven defines the notion of a 'groupId', 'artifactId' and a 'version'. This plugin pulls this information from the Grails project conventions or plugin descriptor.
    Mavenは 'groupId'、'artifactId'、'version'という概念を定義しています。maven-publisherプラグインは、Grailsプロジェクトの規約またはプラグイン識別子からこれらの情報を取得します。

    h5. Projects

    For applications this plugin will use the Grails application name and version provided by Grails when generating the pom.xml file. To change the version you can run the set-version command:

    grails set-version 0.2

    The Maven groupId will be the same as the project name, unless you specify a different one in Config.groovy:


    h5. Plugins

    With a Grails plugin the groupId and version are taken from the following properties in the GrailsPlugin.groovy descriptor:

    String groupId = 'myOrg'
    String version = '0.1'

    The 'artifactId' is taken from the plugin name. For example if you have a plugin called FeedsGrailsPlugin the artifactId will be "feeds". If your plugin does not specify a groupId then this defaults to "org.grails.plugins".
    'artifactId'は、プラグイン名から取得されます。たとえば、FeedsGrailsPluginというプラグインの場合、artifactIdは "feeds"になります。プラグインがgroupIdを指定していない場合、デフォルト設定の"org.grails.plugins"となります。

    4.7.11 プラグイン依存管理

    You can declaratively specify plugins as dependencies via the dependency DSL instead of using the install-plugin command:

    grails.project.dependency.resolution = {
        repositories {

    plugins { runtime ':hibernate:1.2.1' }

    dependencies { … } … }

    If you don't specify a group id the default plugin group id of org.grails.plugins is used.

    h4. Latest Integration

    Latest Integrationラベル

    Only the Ivy dependency manager supports the "latest.integration" version. For Aether you can achieve a similar effect with version ranges.


    You can specify to use the latest version of a particular plugin by using "latest.integration" as the version number:
    バージョン番号として "latest.integration"を使用することで、特定のプラグインの最新バージョンを使用するように指定できます:

    plugins {
        runtime ':hibernate:latest.integration'

    h4. Integration vs. Release

    Integrationラベル vs. Releaseラベル

    The "latest.integration" version label will also include resolving snapshot versions. To not include snapshot versions then use the "latest.release" label:
    "latest.integration"ラベルはスナップショットのバージョンも含まれます。スナップショットのバージョンが含まれないようにするには、 "latest.release"ラベルを使用します。

    plugins {
        runtime ':hibernate:latest.release'

    The "latest.release" label only works with Maven compatible repositories. If you have a regular SVN-based Grails repository then you should use "latest.integration".


    And of course if you use a Maven repository with an alternative group id you can specify a group id:

    plugins {
        runtime 'mycompany:hibernate:latest.integration'

    h4. Plugin Exclusions


    You can control how plugins transitively resolves both plugin and JAR dependencies using exclusions. For example:

    plugins {
        runtime(':weceem:0.8') {
            excludes "searchable"

    Here we have defined a dependency on the "weceem" plugin which transitively depends on the "searchable" plugin. By using the excludes method you can tell Grails not to transitively install the searchable plugin. You can combine this technique to specify an alternative version of a plugin:

    plugins {
        runtime(':weceem:0.8') {
            excludes "searchable" // excludes most recent version
        runtime ':searchable:0.5.4' // specifies a fixed searchable version

    You can also completely disable transitive plugin installs, in which case no transitive dependencies will be resolved:

    plugins {
        runtime(':weceem:0.8') {
            transitive = false
        runtime ':searchable:0.5.4' // specifies a fixed searchable version

    4.7.12 依存管理のキャッシュ

    As a performance optimisation, when using Ivy (this does not apply to Aether), Grails does not resolve dependencies for every command invocation. Even with all the necessary dependencies downloaded and cached, resolution may take a second or two. To minimise this cost, Grails caches the result of dependency resolution (i.e. the location on the local file system of all of the declared dependencies, typically inside the dependency cache) and reuses this result for subsequent commands when it can reasonably expect that nothing has changed.

    Grails only performs dependency resolution under the following circumstances:

    * The project is clean (i.e. fresh checkout or after grails clean)
    • プロジェクトがクリーンな場合(すなわち、チェックアウト直後またはgrails cleanの実行後)

    * The BuildConfig.groovy file has changed since the last command was run
    • 最後にコマンドが実行された後に、BuildConfig.groovyファイルが変更された場合

    * The --refresh-dependencies command line switch is provided to the command (any command)
    • --refresh-dependencies引数が、何らかのコマンドに与えられる場合

    * The refresh-dependencies command is the command being executed
    • refresh-dependenciesコマンドが実行された場合

    Generally, this strategy works well and you can ignore dependency resolution caching. Every time you change your dependencies (i.e. modify BuildConfig.groovy) Grails will do the right thing and resolve your new dependencies.

    However, when you have changing or dynamic dependencies you will have to consider dependency resolution caching.
    しかし、 変化する依存関係 または 動的な依存関係 がある場合は、依存関係解決のキャッシングを考慮する必要があります。

    {info} A changing dependency is one whose version number does not change, but its contents do (like a SNAPSHOT). A dynamic dependency is one that is defined as one of many possible options (like a dependency with a version range, or symbolic version number like latest.integration). {info}

    {info} 変化する依存関係 は、バージョン番号が変更されずに、内容が変化するもの(スナップショットなど)です。 動的な依存関係 は多くの可能なオプションのいずれかとして定義されるものです。(バージョンが範囲指定されている、またはlatest.integrationのように抽象的なバージョン番号を持つ依存関係など) {info}

    Both changing and dynamic dependencies are influenced by the environment. With caching active, any changes to the environment are effectively ignored. For example, your project may not automatically fetch the very latest version of a dependency when using latest.integration. Or if you declare a SNAPSHOT dependency, you may not automatically get the latest that's available on the server.
    変化する依存関係 と 動的な依存関係は共に、リモートリポジトリ等の外部環境に影響されます。キャッシュが有効な場合、これらの環境の変更は事実上無視されます。例えば、latest.integrationを使用している場合、プロジェクトは依存関係の最新バージョンを自動的に取得しないでしょう。また、SNAPSHOTの依存関係を宣言した場合、サーバー上で使用可能な最新のものを自動的に取得できない可能性があります。

    To ensure you have the correct version of a changing or dynamic dependency in your project, you can:
    プロジェクトの 変化する依存関係動的な依存関係 が正しいバージョンであることを確認するために、以下のことができます:

    * clean the project
    • プロジェクトのクリーンアップ

    * run the refresh-dependencies command
    • refresh-dependenciesコマンドの実行

    * run any command with the --refresh-dependencies switch; or
    • 任意のコマンド--refresh-dependenciesを付与して実行

    * make a change to BuildConfig.groovy
    • BuildConfig.groovyを変更

    If you have your CI builds configured to not perform clean builds, it may be worth adding the --refresh-dependencies switch to the command you use to build your projects.

    5 コマンドライン

    Grails' command line system is built on Gant - a simple Groovy wrapper around Apache Ant.
    GrailsのコマンドラインシステムはGant(シンプルなApache AntのGroovyによるラッパー)によって構築されています。

    However, Grails takes it further through the use of convention and the grails command. When you type:

    grails [command name]

    Grails searches in the following directories for Gant scripts to execute:
    • USER_HOME/.grails/scripts
    • PROJECT_HOME/scripts
    • PROJECT_HOME/plugins/*/scripts
    • GRAILS_HOME/scripts

    Grails will also convert command names that are in lower case form such as run-app into camel case. So typing
    Grailsは "run-app" のような小文字のコマンドをキャメルケースに変換して探します。なので次のように入力すると:

    grails run-app

    Results in a search for the following files:
    • USER_HOME/.grails/scripts/RunApp.groovy
    • PROJECT_HOME/scripts/RunApp.groovy
    • PLUGINS_HOME/*/scripts/RunApp.groovy
    • GLOBAL_PLUGINS_HOME/*/scripts/RunApp.groovy
    • GRAILS_HOME/scripts/RunApp.groovy

    If multiple matches are found Grails will give you a choice of which one to execute.

    When Grails executes a Gant script, it invokes the "default" target defined in that script. If there is no default, Grails will quit with an error.

    To get a list of all commands and some help about the available commands type:

    grails help

    which outputs usage instructions and the list of commands Grails is aware of:

    Usage (optionals marked with *):
    grails [environment]* [target] [arguments]*

    Examples: grails dev run-app grails create-app books

    Available Targets (type grails help 'target-name' for more info): grails bootstrap grails bug-report grails clean grails compile ...

    Refer to the Command Line reference in the Quick Reference menu of the reference guide for more information about individual commands

    It's often useful to provide custom arguments to the JVM when running Grails commands, in particular with run-app where you may for example want to set a higher maximum heap size. The Grails command will use any JVM options provided in the general JAVA_OPTS environment variable, but you can also specify a Grails-specific environment variable too:
    Grailsコマンドを実行する際に、JVMへ独自の引数を提供できると便利な場合があります。 例えば、run-appをする際にヒープサイズにより大きな値を設定したいといった場合です。 Grailsコマンドは一般的なJAVA_OPTSの環境変数内で提供されているJVMオプションを使用しますが、Grails固有の環境変数を指定することもできます:

    export GRAILS_OPTS="-Xmx1G -Xms256m -XX:MaxPermSize=256m"
    grails run-app

    h4. non-interactive mode


    When you run a script manually and it prompts you for information, you can answer the questions and continue running the script. But when you run a script as part of an automated process, for example a continuous integration build server, there's no way to "answer" the questions. So you can pass the --non-interactive switch to the script command to tell Grails to accept the default answer for any questions, for example whether to install a missing plugin.
    手動でスクリプト実行する際にユーザ入力を求める場合があります。 そのような場合は質問に応答することでスクリプトの実行が継続されます。 しかし、継続的インテグレーションのビルドサーバといったように、自動化されたプロセスとしてスクリプトを実行する場合は質問に応答する方法がありません。 例えば、未インストールのプラグインをインストールするかどうかといったような質問に対し、デフォルトの値で応答するようGrailsに伝えるには、そのスクリプトコマンドへ--non-interactiveを渡します。

    For example:

    grails war --non-interactive

    5.1 インタラクティブモード

    Interactive mode is the a feature of the Grails command line which keeps the JVM running and allows for quicker execution of commands. To activate interactive mode type 'grails' at the command line and then use TAB completion to get a list of commands:

    If you need to open a file whilst within interactive mode you can use the open command which will TAB complete file paths:

    Even better, the open command understands the logical aliases 'test-report' and 'dep-report', which will open the most recent test and dependency reports respectively. In other words, to open the test report in a browser simply execute open test-report. You can even open multiple files at once: open test-report test/unit/MyTests.groovy will open the HTML test report in your browser and the MyTests.groovy source file in your text editor.

    TAB completion also works for class names after the create-* commands:

    If you need to run an external process whilst interactive mode is running you can do so by starting the command with a !:

    Note that with ! (bang) commands, you get file path auto completion - ideal for external commands that operate on the file system such as 'ls', 'cat', 'git', etc.

    The stop-app command will stop an application that has been run with the run-app command.

    To exit interactive mode enter the exit command. Note that if the Grails application has been run with run-app normally it will terminate when the interactive mode console exits because the JVM will be terminated. An exception to this would be if the application were running in forked mode which means the application is running in a different JVM. In that case the application will be left running afer the interactive mode console terminates. If you want to exit interactive mode and stop an application that is running in forked mode, use the quit command. The quit command will stop the running application and then close interactive mode.

    5.2 フォークモード

    h4. Forked Execution


    Since Grails 2.3, the run-app, run-war, test-app and console commands are now executed in a forked JVM in order to isolate the build classpath from the runtime classpath.
    ランタイムクラスパスからビルドクラスパスを隔離するために、Grails 2.3からrun-apprun-wartest-appconsoleコマンドはフォークされたJVM上で実行されます。

    Forked execution is configured via the grails-app/conf/BuildConfig.groovy file. The following is the default configuration:
    フォーク実行はgrails-app/conf/BuildConfig.groovyファイルで設定します。 以下はデフォルト設定です:

    forkConfig = [maxMemory: 1024, minMemory: 64, debug: false, maxPerm: 256]
    grails.project.fork = [
       test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true], // configure settings for the test-app JVM
       run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256], // configure settings for the run-app JVM
       war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256], // configure settings for the run-war JVM
       console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]// configure settings for the Console UI JVM

    The memory requirements of the forked JVM can be tweaked as per the requirements of the application.

    h4. Forked Test Execution


    When running the test-app command, a separate JVM is launched to execute this tests. This will have a notable impact on the speed of execution of the tests when running the command directly:
    test-appコマンドの実行時、そのテストを実行するための個別のJVMが起動されます。 この起動時間が加算されるため、直接コマンドを実行したときの実行速度はかなりの影響を受けます:

    grails test-app

    To mitigate this, Grails 2.3 and above include a feature that launches a background JVM on standby to run tests when using interactive mode. In other words, running test-app from interactive mode will result in faster test execution times:
    これを緩和するため、Grails 2.3以上には、インタラクティブモード利用時にテスト実行に備えてバックグラウンドでJVMを起動する機能があります。 つまり、インタラクティブモードからのtest-appの実行では、テスト実行時間が速くなります:

    $ grails
    $ grails> test-app

    It is recommended that forked execution is used for tests, however it does require modern hardware due to the use of multiple JVMs. You can therefore disable forked execution by setting the grails.project.fork.test setting to false:
    テストにはフォーク実行の利用をお勧めしますが、複数のJVMを利用するには最新のハードウェアが必要になります。 そのため、grails.project.fork.testfalseにセットすることで、フォーク実行を無効にすることもできます。

    forkConfig = [maxMemory: 1024, minMemory: 64, debug: false, maxPerm: 256]
    grails.project.fork = [
       test: false,

    Using the Test Runnner Deamon to Speed-up Test Execution

    The defaut configuration for the testing is to activate a daemon to run tests using the daemon argument:

    grails.project.fork = [
       test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true], // configure settings for the test-app JVM

    This only works in interactive mode, so if you start Grails with the 'grails' command and then using test-app the daemon will be used:

    $ grails
    $ grails> test-app

    This has the effect of speeding-up test executions times. You can disable the daemon by setting daemon to false. If the daemon becomes unresponsive you can restart it with restart-daemon:

    $ grails> restart-daemon

    Debugging and Forked Execution (debug vs debug-fork)

    An important consideration when using forked execution is that the debug argument will allow a remote debugger to be attached to the build JVM but not the JVM that your application is running in. To debug your application you should use the debug-fork argument:

    grails test-app --debug-fork

    Or for run-app:

    grails run-app --debug-fork

    h4. Forked Tomcat Execution


    Grails 2.2 and above support forked JVM execution of the Tomcat container in development mode. This has several benefits including:
    Grails 2.2以上では、開発モードにおけるTomcatコンテナのフォーク実行をサポートしています。 これにはいくつかのメリットがあります:

    • Reduced memory consumption, since the Grails build system can exit
    • Isolation of the build classpath from the runtime classpath
    • The ability to deploy other Grails/Spring applications in parallels without conflicting dependencies

    • Grailsビルドシステムを終了できるため、メモリ消費量を減らせる
    • ランタイムクラスパスからビルドクラスパスを隔離できる
    • 依存関係のコンフリクトなしに、他のGrails/Springアプリケーションを並列デプロイできる

    To enable forked execution you can set the grails.project.fork.run property to true:


    Then just us the regular run-app command as per normal. Note that in forked mode the grails process will exit and leave the container running in the background. To stop the server there is a new stop-app command:
    それから、いつも通り普通のrun-appコマンドを使います。 フォークモードではgrailsプロセスは終了し、バックグラウンドで実行中のコンテナから切り離されることに注意してください。 サーバを停止するために、新しいstop-appコマンドが用意されています:

    grails stop-app

    To customize the JVM arguments passed to the forked JVM you can specify a map instead:

    grails.project.fork.run= [maxMemory:1024, minMemory:64, debug:false, maxPerm:256, jvmArgs: '..arbitrary JVM arguments..']

    h4. Auto-deploying additional WAR files in Forked Mode


    Since forked execution isolates classpaths more effectively than embedded execution you can deploy additional WAR files (such as other Grails or Spring applications) to the container.

    The easiest way to do so is to drop the WAR files into the src/autodeploy directory (if it doesn't exist you can create it).

    You can customize the location of the autodeploy directory by specifying an alternative location in BuildConfig.groovy:


    h4. Customizing the Forked Tomcat instance


    If you want to programmatically customize the forked Tomcat instance you can do so by implementing a class named org.grails.plugins.tomcat.ForkedTomcatCustomizer which provides a method with the following signature:
    フォークされたTomcatインスタンスをプログラム的にカスタマイズしたい場合は、org.grails.plugins.tomcat.ForkedTomcatCustomizerという名前のクラスを実装します。 このクラスは以下のシグネチャのメソッドを提供します:

    void customize(Tomcat tomcat) {
     // your code here

    5.3 Gantスクリプトの作成

    You can create your own Gant scripts by running the create-script command from the root of your project. For example the following command:

    grails create-script compile-sources

    Will create a script called scripts/CompileSources.groovy. A Gant script itself is similar to a regular Groovy script except that it supports the concept of "targets" and dependencies between them:

    target(default:"The default target is the one that gets executed by Grails") {
        depends(clean, compile)

    target(clean:"Clean out things") { ant.delete(dir:"output") }

    target(compile:"Compile some sources") { ant.mkdir(dir:"mkdir") ant.javac(srcdir:"src/java", destdir:"output") }

    As demonstrated in the script above, there is an implicit ant variable (an instance of groovy.util.AntBuilder) that allows access to the Apache Ant API.
    上記で示したスクリプトのように、暗黙的な変数のantはApache Ant APIを使うことができます。
    In previous versions of Grails (1.0.3 and below), the variable was Ant, i.e. with a capital first letter.

    You can also "depend" on other targets using the depends method demonstrated in the default target above.
    また、上記のdefaultターゲットで示したように、dependsメソッドを使って他のターゲットに 依存させることができます。

    The default target

    In the example above, we specified a target with the explicit name "default". This is one way of defining the default target for a script. An alternative approach is to use the setDefaultTarget() method:

    target("clean-compile": "Performs a clean compilation on the app source") {
        depends(clean, compile)

    target(clean:"Clean out things") { ant.delete(dir:"output") }

    target(compile:"Compile some sources") { ant.mkdir(dir:"mkdir") ant.javac(srcdir:"src/java", destdir:"output") }


    This lets you call the default target directly from other scripts if you wish. Also, although we have put the call to setDefaultTarget() at the end of the script in this example, it can go anywhere as long as it comes after the target it refers to ("clean-compile" in this case).
    こうすることで、他のスクリプトのターゲットを直接デフォルトターゲットに指定できます。setDefaultTarget()は、対象のターゲット(今回の場合は "clean-compile")の後であればどこにでも書くことができます。

    Which approach is better? To be honest, you can use whichever you prefer - there don't seem to be any major advantages in either case. One thing we would say is that if you want to allow other scripts to call your "default" target, you should move it into a shared script that doesn't have a default target at all. We'll talk some more about this in the next section.

    5.4 Grailsスクリプトの再利用

    Grails ships with a lot of command line functionality out of the box that you may find useful in your own scripts (See the command line reference in the reference guide for info on all the commands). Of particular use are the compile, package and bootstrap scripts.

    The bootstrap script for example lets you bootstrap a Spring ApplicationContext instance to get access to the data source and so on (the integration tests use this):

    includeTargets << grailsScript("_GrailsBootstrap")

    target ('default': "Database stuff") { depends(configureProxy, packageApp, classpath, loadApp, configureApp)

    Connection c try { c = appCtx.getBean('dataSource').getConnection() // do something with connection } finally { c?.close() } }

    Pulling in targets from other scripts

    Gant lets you pull in all targets (except "default") from another Gant script. You can then depend upon or invoke those targets as if they had been defined in the current script. The mechanism for doing this is the includeTargets property. Simply "append" a file or class to it using the left-shift operator:

    includeTargets << new File("/path/to/my/script.groovy")
    includeTargets << gant.tools.Ivy
    Don't worry too much about the syntax using a class, it's quite specialised. If you're interested, look into the Gant documentation.

    Core Grailsターゲット
    Core Grails targets

    As you saw in the example at the beginning of this section, you use neither the File- nor the class-based syntax for includeTargets when including core Grails targets. Instead, you should use the special grailsScript() method that is provided by the Grails command launcher (note that this is not available in normal Gant scripts, just Grails ones).
    この章の冒頭の例でお見せしたように、Core Grailsターゲットを含める際に利用するincludeTargetsでは、ファイルベース構文、クラスベース構文のどちらも使用しません。代わりに、Grailsコマンドランチャが提供しているgrailsScript()という特別なメソッドを使用します(このメソッドはGrails専用であり、通常のGantでは利用できません)。

    The syntax for the grailsScript() method is pretty straightforward: simply pass it the name of the Grails script to include, without any path information. Here is a list of Grails scripts that you could reuse:
    _GrailsSettingsYou really should include this! Fortunately, it is included automatically by all other Grails scripts except _GrailsProxy, so you usually don't have to include it explicitly.
    _GrailsEventsInclude this to fire events. Adds an event(String eventName, List args) method. Again, included by almost all other Grails scripts.
    _GrailsClasspathConfigures compilation, test, and runtime classpaths. If you want to use or play with them, include this script. Again, included by almost all other Grails scripts.
    _GrailsProxyIf you don't have direct access to the internet and use a proxy, include this script to configure access through your proxy.
    _GrailsArgParsingProvides a parseArguments target that does what it says on the tin: parses the arguments provided by the user when they run your script. Adds them to the argsMap property.
    _GrailsTestContains all the shared test code. Useful if you want to add any extra tests.
    _GrailsRunProvides all you need to run the application in the configured servlet container, either normally (runApp/runAppHttps) or from a WAR file (runWar/runWarHttps).

    _GrailsEventsイベントトリガーを実装するためのメソッド(event(String eventName, List args))を使用するには、これをインクルードする必要があります。このスクリプトもほぼ全てのGrailsスクリプトでインクルードされています。
    _GrailsClasspathコンパイル、テスト、およびランタイムのクラスパスを設定します。このスクリプトもほぼ全ての Grailsスクリプトでインクルードされています。

    There are many more scripts provided by Grails, so it is worth digging into the scripts themselves to find out what kind of targets are available. Anything that starts with an "_" is designed for reuse.
    Grailsではもっと多くのスクリプトが提供されていますので、どんな種類のターゲットが利用可能かを調べてみる価値があるでしょう。" "で始まっているものはすべて再利用されることを考慮してデザインされています。

    Script architecture

    You maybe wondering what those underscores are doing in the names of the Grails scripts. That is Grails' way of determining that a script is _internal , or in other words that it has not corresponding "command". So you can't run "grails _grails-settings" for example. That is also why they don't have a default target.

    Internal scripts are all about code sharing and reuse. In fact, we recommend you take a similar approach in your own scripts: put all your targets into an internal script that can be easily shared, and provide simple command scripts that parse any command line arguments and delegate to the targets in the internal script. For example if you have a script that runs some functional tests, you can split it like this:


    includeTargets << new File("${basedir}/scripts/_FunctionalTests.groovy")

    target(default: "Runs the functional tests for this project.") { depends(runFunctionalTests) }


    includeTargets << grailsScript("_GrailsTest")

    target(runFunctionalTests: "Run functional tests.") { depends(...) … }

    Here are a few general guidelines on writing scripts:

    • Split scripts into a "command" script and an internal one.
    • Put the bulk of the implementation in the internal script.
    • Put argument parsing into the "command" script.
    • To pass arguments to a target, create some script variables and initialise them before calling the target.
    • Avoid name clashes by using closures assigned to script variables instead of targets. You can then pass arguments direct to the closures.

    • スクリプトを"コマンドスクリプト"と"内部スクリプト"に分割します。
    • 実装の大部分は"内部スクリプト"で行います。
    • 引数の解析は"コマンドスクリプト"で行います。
    • ターゲットに引数を渡すには、いくつかのスクリプト変数を作成し、ターゲットを呼び出す前にそれらを初期化します。
    • ターゲットの代わりにスクリプト変数に割り当てられているクロージャを使用して名前の衝突を避けるようにします。そうすれば、引数をクロージャに直接渡すことができます。

    5.5 イベントを取得する

    Grails provides the ability to hook into scripting events. These are events triggered during execution of Grails target and plugin scripts.

    The mechanism is deliberately simple and loosely specified. The list of possible events is not fixed in any way, so it is possible to hook into events triggered by plugin scripts, for which there is no equivalent event in the core target scripts.

    Defining event handlers

    Event handlers are defined in scripts called _Events.groovy. Grails searches for these scripts in the following locations:

    • USER_HOME/.grails/scripts - user-specific event handlers
    • PROJECT_HOME/scripts - applicaton-specific event handlers
    • PLUGINS_HOME/*/scripts - plugin-specific event handlers
    • GLOBAL_PLUGINS_HOME/*/scripts - event handlers provided by global plugins

    • USER_HOME/.grails/scripts - ユーザー固有のイベントハンドラ
    • PROJECT_HOME/scripts - アプリケーション固有のイベントハンドラ
    • PLUGINS_HOME/*/scripts - プラグイン固有のイベントハンドラ
    • GLOBAL_PLUGINS_HOME/*/scripts - グローバルプラグインによって提供されているイベントハンドラ

    Whenever an event is fired, all the registered handlers for that event are executed. Note that the registration of handlers is performed automatically by Grails, so you just need to declare them in the relevant _Events.groovy file.
    イベントが発生するたびに登録されている すべての ハンドラが実行されます。ハンドラの登録はGrailsによって自動的に行われることに注意してください。なので、必要な作業は関連する_Events.groovyファイルにそれらを宣言するだけです。

    Event handlers are blocks defined in _Events.groovy, with a name beginning with "event". The following example can be put in your /scripts directory to demonstrate the feature:
    イベントハンドラは _Events.groovy で定義されている名前が "event" で始まっているブロックです。次の例のように_Events.groovyを記述して、/scripts ディレクトリに配置することによって、イベントハンドラを実装することができます:

    eventCreatedArtefact = { type, name ->
       println "Created $type $name"

    eventStatusUpdate = { msg -> println msg }

    eventStatusFinal = { msg -> println msg }

    You can see here the three handlers eventCreatedArtefact, eventStatusUpdate, eventStatusFinal. Grails provides some standard events, which are documented in the command line reference guide. For example the compile command fires the following events:
    ここでは三つのハンドラが指定されています。eventCreatedArtefacteventStatusUpdateeventStatusFinal。Grailsはいくつかの標準的なイベントを提供しています。詳細はコマンドラインリファレンスガイドを参照してください。たとえば、 compileコマンドは、次のようなイベントを発行させます。
    • CompileStart - Called when compilation starts, passing the kind of compile - source or tests
    • CompileEnd - Called when compilation is finished, passing the kind of compile - source or tests

    • CompileStart - sourceまたはtestsコンパイル開始時に発行されます。
    • CompileEnd - sourceまたはtestsコンパイル終了時に発行されます。

    Triggering events

    To trigger an event simply include the Init.groovy script and call the event() closure:
    イベントを発行するには _GrailsEvents.groovy スクリプトをインクルードしてevent()クロージャを使用します:

    includeTargets << grailsScript("_GrailsEvents")

    event("StatusFinal", ["Super duper plugin action complete!"])

    Common Events

    Below is a table of some of the common events that can be leveraged:

    StatusUpdatemessagePassed a string indicating current script status/progress
    StatusErrormessagePassed a string indicating an error message from the current script
    StatusFinalmessagePassed a string indicating the final script status message, i.e. when completing a target, even if the target does not exit the scripting environment
    CreatedArtefactartefactType,artefactNameCalled when a create-xxxx script has completed and created an artefact
    CreatedFilefileNameCalled whenever a project source filed is created, not including files constantly managed by Grails
    ExitingreturnCodeCalled when the scripting environment is about to exit cleanly
    PluginInstalledpluginNameCalled after a plugin has been installed
    CompileStartkindCalled when compilation starts, passing the kind of compile - source or tests
    CompileEndkindCalled when compilation is finished, passing the kind of compile - source or tests
    DocStartkindCalled when documentation generation is about to start - javadoc or groovydoc
    DocEndkindCalled when documentation generation has ended - javadoc or groovydoc
    SetClasspathrootLoaderCalled during classpath initialization so plugins can augment the classpath with rootLoader.addURL(...). Note that this augments the classpath after event scripts are loaded so you cannot use this to load a class that your event script needs to import, although you can do this if you load the class by name.
    PackagingEndnoneCalled at the end of packaging (which is called prior to the Tomcat server being started and after web.xml is generated)

    StatusErrormessage実行されているスクリプトのエラーメッセージを 知らせる
    StatusFinalmessageスクリプトの終了時に最終メッセージを知らせる。 スクリプトによっては完全終了時ではなく、コマ ンドの終了時に動作する
    CreatedArtefactartefactType,artefactNamecreate-xxxxなどのアーティファクト生成スクリプトが、アーティファクトの生成完了時にアーティ ファクトタイプとアーティファクト名を知らせる
    CreatedFilefileNameファイルがスクリプトによって生成されたときに ファイル名を知らせる
    ExitingreturnCodeスクリプトが正常に終了したときに終了コードを 知らせる
    PluginInstalledpluginNameプラグインのインストールが終了した後にプラグイン 名を知らせる
    CompileStartkindコンパイル開始時にコンパイルする種類(source または tests)を知らせる
    CompileEndkindコンパイル終了時にコンパイルした種類(source または tests)を知らせる
    DocStartkindドキュメント生成時に、どのドキュメント生成(javadoc または groovydoc)が開始するかを知らせる
    DocEndkindドキュメント生成完了時に、どのドキュメント生成(javadoc または groovydoc)が完了したかを知らせる
    SetClasspathrootLoaderクラスパス初期化中にGrailsRootLoader が渡されるので、「rootLoader.addURL( … )」でクラスをGrailsRootLoader に追加できる
    PackagingEndnoneGrailsアプリケーションのパッケージング完了時 (web.xml生成後、Tomcatサーバ起動前)に呼び出される

    5.6 ビルドのカスタマイズ

    Grails is most definitely an opinionated framework and it prefers convention to configuration, but this doesn't mean you can't configure it. In this section, we look at how you can influence and modify the standard Grails build.

    The defaults

    The core of the Grails build configuration is the grails.util.BuildSettings class, which contains quite a bit of useful information. It controls where classes are compiled to, what dependencies the application has, and other such settings.
    ビルド設定の中心部分は、ビルド時に有用な情報が含まれている grails.util.BuildSettingsクラスです。このクラスは、どこにコンパイルされるのか、アプリケーションが何に依存関係を持っているのか、どのような設定を保持しているのか、を制御します。

    Here is a selection of the configuration options and their default values:
    PropertyConfig optionDefault value

    The BuildSettings class has some other properties too, but they should be treated as read-only:
    baseDirThe location of the project.
    userHomeThe user's home directory.
    grailsHomeThe location of the Grails installation in use (may be null).
    grailsVersionThe version of Grails being used by the project.
    grailsEnvThe current Grails environment.
    configThe configuration settings defined in the project's BuildConfig.groovy file. Access properties in the same way as you access runtime settings: grailsSettings.config.foo.bar.hello.
    compileDependenciesA list of compile-time project dependencies as File instances.
    testDependenciesA list of test-time project dependencies as File instances.
    runtimeDependenciesA list of runtime-time project dependencies as File instances.

    configプロジェクトの BuildConfig.groovy に定義された設定。ランタイム時と同様にプロパティにアクセスできます: grailsSettings.config.foo.bar.hello

    Of course, these properties aren't much good if you can't get hold of them. Fortunately that's easy to do: an instance of BuildSettings is available to your scripts as the grailsSettings script variable. You can also access it from your code by using the grails.util.BuildSettingsHolder class, but this isn't recommended.

    Overriding the defaults

    All of the properties in the first table can be overridden by a system property or a configuration option - simply use the "config option" name. For example, to change the project working directory, you could either run this command:
    grails -Dgrails.project.work.dir=work compile
    or add this option to your grails-app/conf/BuildConfig.groovy file:
    grails.project.work.dir = "work"
    Note that the default values take account of the property values they depend on, so setting the project working directory like this would also relocate the compiled classes, test classes, resources, and plugins.

    What happens if you use both a system property and a configuration option? Then the system property wins because it takes precedence over the BuildConfig.groovy file, which in turn takes precedence over the default values.

    The BuildConfig.groovy file is a sibling of grails-app/conf/Config.groovy - the former contains options that only affect the build, whereas the latter contains those that affect the application at runtime. It's not limited to the options in the first table either: you will find build configuration options dotted around the documentation, such as ones for specifying the port that the embedded servlet container runs on or for determining what files get packaged in the WAR file.

    Available build settings

    grails.server.port.httpPort to run the embedded servlet container on ("run-app" and "run-war"). Integer.
    grails.server.port.httpsPort to run the embedded servlet container on for HTTPS ("run-app --https" and "run-war --https"). Integer.
    grails.config.base.webXmlPath to a custom web.xml file to use for the application (alternative to using the web.xml template).
    grails.compiler.dependenciesLegacy approach to adding extra dependencies to the compiler classpath. Set it to a closure containing "fileset()" entries. These entries will be processed by an AntBuilder so the syntax is the Groovy form of the corresponding XML elements in an Ant build file, e.g. fileset(dir: "$basedir/lib", includes: "**/*.class").
    grails.testing.patternsA list of Ant path patterns that let you control which files are included in the tests. The patterns should not include the test case suffix, which is set by the next property.
    grails.testing.nameSuffixBy default, tests are assumed to have a suffix of "Tests". You can change it to anything you like but setting this option. For example, another common suffix is "Test".
    grails.project.war.fileA string containing the file path of the generated WAR file, along with its full name (include extension). For example, "target/my-app.war".
    grails.war.dependenciesA closure containing "fileset()" entries that allows you complete control over what goes in the WAR's "WEB-INF/lib" directory.
    grails.war.copyToWebAppA closure containing "fileset()" entries that allows you complete control over what goes in the root of the WAR. It overrides the default behaviour of including everything under "web-app".
    grails.war.resourcesA closure that takes the location of the staging directory as its first argument. You can use any Ant tasks to do anything you like. It is typically used to remove files from the staging directory before that directory is jar'd up into a WAR.
    grails.project.web.xmlThe location to generate Grails' web.xml to

    grails.server.port.http組み込みのサーブレットコンテナを実行するポート番号。("run-app" と "run-war")
    grails.server.port.httpsHTTPS用の組み込みのサーブレットコンテナを実行するポート番号。("run-app --https"と"run-war --https")
    grails.project.war.file生成されるWARファイルの名称(拡張子を含む)のファイルパス。例として、"target/my-app.war" 等。

    Reloading Agent Cache Directory

    Grails uses an agent based reloading system in the development environment that allows source code changes to be picked up while the application is running. This reloading agent caches information needed to carry out the reloading efficiently. By default this information is stored under <USER_HOME_DIR>/.grails/.slcache/. The GRAILS_AGENT_CACHE_DIR environment variable may be assigned a value to cause this cache information to be stored somewhere else. Note that this is an operating system environment variable, not a JVM system property or a property which may be defined in BuildConfig.groovy. This setting must be defined as an environment variable because the agent cache directory must be configured very early in the JVM startup process, before any Grails code is executed.

    5.7 AntとMaven

    If all the other projects in your team or company are built using a standard build tool such as Ant or Maven, you become the black sheep of the family when you use the Grails command line to build your application. Fortunately, you can easily integrate the Grails build system into the main build tools in use today (well, the ones in use in Java projects at least).

    Ant Integration

    When you create a Grails application with the create-app command, Grails doesn't automatically create an Ant build.xml file but you can generate one with the integrate-with command:
    create-appコマンドでGrailsアプリケーションを作成した際に、Grailsは自動的にはApache Antのbuild.xmlを生成しません。integrate-withコマンドを使用して生成することが可能です。

    grails integrate-with --ant

    This creates a build.xml file containing the following targets:
    • clean - Cleans the Grails application
    • compile - Compiles your application's source code
    • test - Runs the unit tests
    • run - Equivalent to "grails run-app"
    • war - Creates a WAR file
    • deploy - Empty by default, but can be used to implement automatic deployment

    • clean - Grailsアプリケーションをクリーンします。
    • compile - アプリケーションのソースコードをコンパイルします。
    • test - ユニットテストを実行します。
    • run - Grailsの"run-app"コマンド相当を実行します。
    • war - WARファイルを作成します。
    • deploy - デフォルトでは空ですが、自動配備を実装することができます。

    Each of these can be run by Ant, for example:

    ant war

    The build file is configured to use Apache Ivy for dependency management, which means that it will automatically download all the requisite Grails JAR files and other dependencies on demand. You don't even have to install Grails locally to use it! That makes it particularly useful for continuous integration systems such as CruiseControl or Jenkins.
    ビルドファイルは Apache Ivy をの依存性管理を使う準備ができています。必要に応じてGrailsが利用したり、またはそれ以外で利用される依存関係のあるJARファイルを自動的にダウンロードしてくることができるということです。それを使うにはローカルにGrailsをインストールする必要すらありません!CruiseControlJenkinsのような継続的インテグレーションツールを使う場合、特に便利でしょう。

    It uses the Grails Ant task to hook into the existing Grails build system. The task lets you run any Grails script that's available, not just the ones used by the generated build file. To use the task, you must first declare it:
    <taskdef name="grailsTask"

    This raises the question: what should be in "grails.classpath"? The task itself is in the "grails-bootstrap" JAR artifact, so that needs to be on the classpath at least. You should also include the "groovy-all" JAR. With the task defined, you just need to use it! The following table shows you what attributes are available:
    ここで疑問が生じます。どれが"grails.classpath"でしょうか。タスク自体は"grails-bootstrap"JARの一部です。なので、少なくともクラスパス上にある必要があります。また、"groovy-all" JARを含める必要があります。タスク宣言ではこれらを仕使用する必要があります!次の表は、どんな属性が利用可能かを示しています。
    homeThe location of the Grails installation directory to use for the build.Yes, unless classpath is specified.
    classpathrefClasspath to load Grails from. Must include the "grails-bootstrap" artifact and should include "grails-scripts".Yes, unless home is set or you use a classpath element.
    scriptThe name of the Grails script to run, e.g. "TestApp".Yes.
    argsThe arguments to pass to the script, e.g. "-unit -xml".No. Defaults to "".
    environmentThe Grails environment to run the script in.No. Defaults to the script default.
    includeRuntimeClasspathAdvanced setting: adds the application's runtime classpath to the build classpath if true.No. Defaults to true.

    scriptGrailsスクリプトの実行名。例えば "TestApp"。必須です。
    argsスクリプトに渡す引数。例えば "-unix -xml"。必須ではありません。デフォルトは "" です。
    includeRuntimeClasspath高度な設定です。 trueの場合、アプリケーション実行時クラスパスをクラスパスに追加します。必須ではありません。 デフォルトはtrueです。

    The task also supports the following nested elements, all of which are standard Ant path structures:

    • classpath - The build classpath (used to load Gant and the Grails scripts).
    • compileClasspath - Classpath used to compile the application's classes.
    • runtimeClasspath - Classpath used to run the application and package the WAR. Typically includes everything in @compileClasspath.
    • testClasspath - Classpath used to compile and run the tests. Typically includes everything in runtimeClasspath.

    • classpath - ビルド時のクラスパス。(GantとGrailsスクリプトロード時に使用)
    • compileClasspath - アプリケーションコンパイル時のクラスパス。
    • runtimeClasspath - アプリケーションとWARパッケージ実行時のクラスパス。通常compileClasspathに全てが含まれます。
    • testClasspath - コンパイル時と、テスト実行時のクラスパス。通常runtimeClasspathに全てが含まれます。

    How you populate these paths is up to you. If you use the home attribute and put your own dependencies in the lib directory, then you don't even need to use any of them. For an example of their use, take a look at the generated Ant build file for new apps.

    Maven Integration

    Grails provides integration with Maven 2 with a Maven plugin.
    GrailsはMavenプラグインを介して Maven 2":http://maven.apache.org との統合を提供しています。


    In order to use the Maven plugin, all you need is Maven 2 installed and set up. This is because you no longer need to install Grails separately to use it with Maven!

    The Maven 2 integration for Grails has been designed and tested for Maven 2.0.9 and above. It will not work with earlier versions.
    GrailsのMaven2統合は、Maven 2.0.9以上を対象として設計・テストされています。それ以前のバージョンでは動作しません。

    The default mvn setup DOES NOT supply sufficient memory to run the Grails environment. We recommend that you add the following environment variable setting to prevent poor performance:

    export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256"

    Creating a Grails Maven Project

    Using the create-pom command you can generate a valid Maven pom.xml file for any existing Grails project. The below presents an example:
    create-pom コマンドを使用することで、既存のGrailsプロジェクトに対して、Mavenの pom.xml を作成する事ができます。次のように実行します:

    $ grails create-app myapp
    $ cd myapp
    $ grails create-pom com.mycompany

    The create-pom command expects a group id as an argument. The name and the version are taken from the application.properties of the application. The Maven plugin will keep the version in the pom.xml in sync with the version in application.properties.
    create-pom コマンドには引数としてグループIDを指定することができます。バージョン番号は、アプリケーションの application.properties から取得します。 Mavenプラグインは、常に pom.xml のバージョンと application.properties のバージョンを同期します。

    The following standard Maven commands are then possible:

    • compile - Compiles a Grails project
    • package - Builds a WAR file from the Grails project.
    • install - Builds a WAR file (or plugin zip/jar if a plugin) and installs it into your local Maven cache
    • test - Runs the tests of a Grails project
    • clean - Cleans the Grails project

    • compile - Grailsプロジェクトをコンパイル
    • package - GrailsプロジェクトのWARファイルをビルドする
    • install - WARファイル(又はプラグインの場合はZIPかJAR)をビルドしてMavenローカルキャッシュにインストールします
    • test - Grailsプロジェクトのテストを実行します
    • clean - Grailsプロジェクトをクリーンします

    Other standard Maven commands will likely work too.

    You can also use some of the Grails commands that have been wrapped as Maven goals:

    • grails:create-controller - create-controllerコマンドを呼び出します
    • grails:create-domain-class - create-domain-classコマンドを呼び出します
    • grails:create-integration-test - create-integration-testコマンドを呼び出します
    • grails:create-pom - 既存のGrailsプロジェクトにMaven POMを新規作成します
    • grails:create-script - create-scriptコマンドを呼び出します
    • grails:create-service - create-serviceコマンドを呼び出します
    • grails:create-taglib - create-tag-libコマンドを呼び出します
    • grails:create-unit-test - create-unit-testコマンドを呼び出します
    • grails:exec - 任意のGrailsコマンドラインスクリプトを実行します
    • grails:generate-all - generate-allコマンドを呼び出します
    • grails:generate-controller - generate-controllerコマンドを呼び出します
    • grails:generate-views - generate-viewsコマンドを呼び出します
    • grails:install-templates - install-templatesコマンドを呼び出します
    • grails:list-plugins - list-pluginsコマンドを呼び出します
    • grails:package - packageコマンドを呼び出します
    • grails:run-app - run-appコマンドを呼び出します

    For a complete, up to date list, run mvn grails:help
    最新のリストを見るには、 mvn grails:help を実行してください。

    Archetypeを使用したGrails Mavenプロジェクトの作成
    Creating a Grails Maven Project using the Archetype

    You can create a Maven Grails project without having Grails installed, simply run the following command:
    Grailsのインストール無しでMaven Grailsプロジェクトの作成が可能です。次のコマンドを実行します:

    mvn archetype:generate -DarchetypeGroupId=org.grails \
        -DarchetypeArtifactId=grails-maven-archetype \
        -DarchetypeVersion=2.1.0.RC1 \
        -DgroupId=example -DartifactId=my-app

    Choose whichever grails version, group ID and artifact ID you want for your application, but everything else must be as written. This will create a new Maven project with a POM and a couple of other files. What you won't see is anything that looks like a Grails application. So, the next step is to create the project structure that you're used to.
    But first, to set target JDK to Java 6, do that now. Open my-app/pom.xml and change
    はじめに、ターゲットJDKをJava 6にセットします。my-app/pom.xmlを開いて、次のように変更します:


    Then you're ready to create the project structure:

    cd my-app
    mvn initialize

    Defining Plugin Dependencies

    All Grails plugins are published to a standard Maven repository located at . When using the Maven plugin for Grails you must ensure that this repository is declared in your list of remote repositories: 全ての公式Grailsプラグインは、のMavenリポジトリに公開されています。Mavenプラグインを使用する場合は、リモートリポジトリの定義にリポジトリが追加されている必要があります。


    With this done you can declare plugin dependencies within your pom.xml file:
    この設定が完了したら、 pom.xml ファイルに、プラグイン依存定義を行います:


    Note that the type element must be set to zip.
    注意点としては、 type エレメントの定義は zip となる部分です。

    Forked Grails Execution

    By default the Maven plugin will run Grails commands in-process, meaning that the Grails process occupies the same JVM as the Maven process. This can put strain on the Maven process for particularly large applications.

    In this case it is recommended to use forked execution. Forked execution can be configured in the configuration element of the plugin:

            <!-- Whether for Fork a JVM to run Grails commands -->

    With this configuration in place a separate JVM will be forked when running Grails commands. If you wish to debug the JVM that is forked you can add the forkDebug element:

    <!-- Whether for Fork a JVM to run Grails commands -->

    If you need to customize the memory of the forked process the following elements are available:

    • forkMaxMemory - The maximum amount of heap (default 1024)
    • forkMinMemory - The minimum amount of heap (default 512)
    • forkPermGen - The amount of permgen (default 256)

    Multi Module Maven Builds

    The Maven plugin can be used to power multi-module Grails builds. The easiest way to set this is up is with the create-multi-project-build command:

    $ grails create-app myapp
    $ grails create-plugin plugin1
    $ grails create-plugin plugin2
    $ grails create-multi-project-build org.mycompany:parent:1.0

    Running mvn install will build all projects together. To enable the 'grails' command to read the POMs you can modify BuildConfig.groovy to use the POM and resolve dependencies from your Maven local cache:

    grails.project.dependency.resolution = {
        pom true
        repositories {

    By reading the pom.xml file you can do an initial mvn install from the parent project to build all plugins and install them into your local maven cache and then cd into your project and use the regular grails run-app command to run your application. All previously built plugins will be resolved from the local Maven cache.

    Adding Grails commands to phases

    The standard POM created for you by Grails already attaches the appropriate core Grails commands to their corresponding build phases, so "compile" goes in the "compile" phase and "war" goes in the "package" phase. That doesn't help though when you want to attach a plugin's command to a particular phase. The classic example is functional tests. How do you make sure that your functional tests (using which ever plugin you have decided on) are run during the "integration-test" phase?
    Grailsが作成した標準のPOMファイルは、Grailsのビルドフェーズに対応したコアコマンドに適切に付属しています。"compile" は "compile"フェーズに、"war" は "package"フェーズに。特定のフェーズにプラグインコマンドを付属させたい場合には役立ちません。古典的な例は、ファンクショナルテストです。どうやってファンクショナルテストが統合テストフェーズの間に(あなた使用しているどんなプラグインを使った場合でも)実行されるのかを確かめるのでしょうか?

    Fear not: all things are possible. In this case, you can associate the command to a phase using an extra "execution" block:
            <!-- Add the "functional-tests" command to the "integration-test" phase -->

    This also demonstrates the grails:exec goal, which can be used to run any Grails command. Simply pass the name of the command as the command system property, and optionally specify the arguments with the args property:
    またこれは grails:exec goal の実演にもなっています。Grailsのどんなコマンドも実行できるのです。単にコマンド名を渡すcommandシステムプロパティと、オプションで引数を渡すargsプロパティがあります:

    mvn grails:exec -Dcommand=create-webtest -Dargs=Book

    Debugging a Grails Maven Project

    Maven can be launched in debug mode using the "mvnDebug" command. To launch your Grails application in debug, simply run:
    Mavenは "mvnDebug" コマンドを使用して、デバッグモードで起動することができます。デバッグでGrailsアプリケーションを起動するには、単純に以下のコマンドを実行します:

    mvnDebug grails:run-app

    The process will be suspended on startup and listening for a debugger on port 8000.

    If you need more control of the debugger, this can be specified using the MAVEN_OPTS environment variable, and launch Maven with the default "mvn" command:
    デバッガのより詳細に制御する必要がある場合は、環境変数のMAVEN_OPTSを指定して標準の "mvn" コマンドを使用してMavenを起動させます。

    MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
    mvn grails:run-app

    Raising issues

    If you come across any problems with the Maven integration, please raise a JIRA issue.
    Maven統合を使っている際になにか問題に直面した場合、JIRA issueに問題を提起して下さい。

    5.8 Grailsラッパー

    The Grails Wrapper allows a Grails application to built without having to install Grails and configure a GRAILS_HOME environment variable. The wrapper includes a small shell script and a couple of small bootstrap jar files that typically would be checked in to source code control along with the rest of the project. The first time the wrapper is executed it will download and configure a Grails installation. This wrapper makes it more simple to setup a development environment, configure CI and manage upgrades to future versions of Grails. When the application is upgraded to the next version of Grails, the wrapper is updated and checked in to the source code control system and the next time developers update their workspace and run the wrapper, they will automatically be using the correct version of Grails.

    Generating The Wrapper

    The wrapper command can be used to generate the wrapper shell scripts and supporting jar files. Execute the wrapper command at the top of an existing Grails project.

    grails wrapper

    In order to do this of course Grails must be installed and configured. This is only a requirement for bootstrapping the wrapper. Once the wrapper is generated there is no need to have a Grails installation configured in order to use the wrapper.

    See the wrapper command documentation for details about command line arguments.

    By default the wrapper command will generate a grailsw shell script and grailsw.bat batch file at the top of the project. In addition to those, a wrapper/ directory (the name of the directory is configurable via command line options) is generated which contains some support files which are necessary to run the wrapper. All of these files should be checked into the source code control system along with the rest of the project. This allows developers to check the project out of source code control and immediately start using the wrapper to execute Grails commands without having to install and configure Grails.

    Using The Wrapper

    The wrapper script accepts all of the same arguments as the normal grails command.

    ./grailsw create-domain-class com.demo.Person
    ./grailsw run-app
    ./grailsw test-app unit:


    6 O/Rマッピング (GORM)

    Domain classes are core to any business application. They hold state about business processes and hopefully also implement behavior. They are linked together through relationships; one-to-one, one-to-many, or many-to-many.

    ドメインクラスは業務アプリケーションの中心です。 それらは業務プロセスについての状態や振る舞いを保持します。 また、それらは1対1、1対多、多対多などの関連を通して結びつけられます。

    GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate 3 (a very popular and flexible open source ORM solution) and thanks to the dynamic nature of Groovy with its static and dynamic typing, along with the convention of Grails, there is far less configuration involved in creating Grails domain classes.

    GORMは、Grailsのオブジェクトリレーショナルマッピング(ORM)の実装です。 その裏では、広く使われていて柔軟性の高いオープンソースORMであるHibernate 3を利用しています。 Grailsの規約と、静的・動的型付けというGroovyのダイナミックな特性のおかげで、Grailsのドメインクラスに必要となる設定はほとんどありません。

    You can also write Grails domain classes in Java. See the section on Hibernate Integration for how to write domain classes in Java but still use dynamic persistent methods. Below is a preview of GORM in action:

    GrailsのドメインクラスをJavaで書くこともできます。 Javaでドメインクラスを書いて、動的な永続化メソッドも使えるようにする方法については、GrailsとHibernateのセクションを参照してください。


    def book = Book.findByTitle("Groovy in Action")

    book .addToAuthors(name:"Dierk Koenig") .addToAuthors(name:"Guillaume LaForge") .save()

    6.1 クイックスタートガイド

    A domain class can be created with the create-domain-class command:

    grails create-domain-class helloworld.Person

    If no package is specified with the create-domain-class script, Grails automatically uses the application name as the package name.

    This will create a class at the location grails-app/domain/helloworld/Person.groovy such as the one below:

    package helloworld

    class Person { }

    If you have the dbCreate property set to "update", "create" or "create-drop" on your DataSource, Grails will automatically generate/modify the database tables for you.
    データソースdbCreateプロパティに"update", "create" または "create-drop"が設定されている場合は、ドメインクラスに対応したデータベースのテーブルを自動的に作成/修正します。

    You can customize the class by adding properties:

    class Person {
        String name
        Integer age
        Date lastVisit

    Once you have a domain class try and manipulate it with the shell or console by typing:

    grails console

    This loads an interactive GUI where you can run Groovy commands with access to the Spring ApplicationContext, GORM, etc.
    このコマンドはGroovyコードを実行可能なインタラクティブなGUIを起動します。GroovyコードからSpring ApplicationContextやGORMなどを使用できます。

    6.1.1 基本CRUD

    Try performing some basic CRUD (Create/Read/Update/Delete) operations.

    h4. Create


    To create a domain class use Map constructor to set its properties and call save:

    def p = new Person(name: "Fred", age: 40, lastVisit: new Date())

    The save method will persist your class to the database using the underlying Hibernate ORM layer.

    h4. Read


    Grails transparently adds an implicit id property to your domain class which you can use for retrieval:

    def p = Person.get(1)
    assert 1 == p.id

    This uses the get method that expects a database identifier to read the Person object back from the database.
    You can also load an object in a read-only state by using the read method:

    def p = Person.read(1)

    In this case the underlying Hibernate engine will not do any dirty checking and the object will not be persisted. Note that
    if you explicitly call the save method then the object is placed back into a read-write state.
    読み取り専用でオブジェクトを参照した場合は、下層のHibernateはdirtyチェックと永続化処理を行いません。 しかし、saveメソッドを明示的に呼び出した時は、オブジェクトは読み書き可能な状態に戻るということに留意してください。

    In addition, you can also load a proxy for an instance by using the load method:

    def p = Person.load(1)

    This incurs no database access until a method other than getId() is called. Hibernate then initializes the proxied instance, or
    throws an exception if no record is found for the specified id.

    h4. Update


    To update an instance, change some properties and then call save again:

    def p = Person.get(1)
    p.name = "Bob"

    h4. Delete


    To delete an instance use the delete method:

    def p = Person.get(1)

    6.2 GORMでのドメインモデリング

    When building Grails applications you have to consider the problem domain you are trying to solve. For example if you were building an Amazon-style bookstore you would be thinking about books, authors, customers and publishers to name a few.

    These are modeled in GORM as Groovy classes, so a Book class may have a title, a release date, an ISBN number and so on. The next few sections show how to model the domain in GORM.

    To create a domain class you run the create-domain-class command as follows:

    grails create-domain-class org.bookstore.Book

    The result will be a class at grails-app/domain/org/bookstore/Book.groovy:

    package org.bookstore

    class Book { }

    This class will map automatically to a table in the database called book (the same name as the class). This behaviour is customizable through the ORM Domain Specific Language

    Now that you have a domain class you can define its properties as Java types. For example:

    package org.bookstore

    class Book { String title Date releaseDate String ISBN }

    Each property is mapped to a column in the database, where the convention for column names is all lower case separated by underscores. For example releaseDate maps onto a column release_date. The SQL types are auto-detected from the Java types, but can be customized with Constraints or the ORM DSL.

    6.2.1 GORMでの関連

    Relationships define how domain classes interact with each other. Unless specified explicitly at both ends, a relationship exists only in the direction it is defined.
    ドメインクラスがどのように相互作用するのかを関連として定義します。両側のドメインクラスで明確に関連が定義されていない限り、関連はそれが定義された方向にだけ存在します。 多対1、1対1 (Many-to-One, One-to-one)

    A many-to-one relationship is the simplest kind, and is defined with a property of the type of another domain class. Consider this example:

    Example A

    class Face {
        Nose nose

    class Nose {

    In this case we have a unidirectional many-to-one relationship from Face to Nose. To make this relationship bidirectional define the other side as follows (and see the section on controlling the ends of the association just below):

    Example B

    class Face {
        Nose nose

    class Nose {
        static belongsTo = [face:Face]

    In this case we use the belongsTo setting to say that Nose "belongs to" Face. The result of this is that we can create a Face, attach a Nose instance to it and when we save or delete the Face instance, GORM will save or delete the Nose. In other words, saves and deletes will cascade from Face to the associated Nose:

    new Face(nose:new Nose()).save()

    The example above will save both face and nose. Note that the inverse is not true and will result in an error due to a transient Face:

    new Nose(face:new Face()).save() // will cause an error
    new Nose(face:new Face()).save() // 意図しない動作 Noseは保存されるが、Faceは保存されない

    Now if we delete the Face instance, the Nose will go too:

    def f = Face.get(1)
    f.delete() // both Face and Nose deleted
    def f = Face.get(1)
    f.delete() // FaseとNose両方が削除される

    To make the relationship a true one-to-one, use the hasOne property on the owning side, e.g. Face:

    Example C

    class Face {
        static hasOne = [nose:Nose]

    class Nose {
        Face face

    Note that using this property puts the foreign key on the inverse table to the previous example, so in this case the foreign key column is stored in the nose table inside a column called face_id. Also, hasOne only works with bidirectional relationships.
    1つ前のExample Bでは、faceテーブルにnoseテーブルへの外部キーが生成されますが、このプロパティを使用すると外部キーが作成されるテーブルが逆になる点に注意してください。この例だと、noseテーブルにface_idカラムが追加されます。hasOneも双方向の関連としてのみ動作します。

    Finally, it's a good idea to add a unique constraint on one side of the one-to-one relationship:

    class Face {
        static hasOne = [nose:Nose]

    static constraints = { nose unique: true } }

    class Nose {
        Face face

    h5. Controlling the ends of the association

    Occasionally you may find yourself with domain classes that have multiple properties of the same type. They may even be self-referential, i.e. the association property has the same type as the domain class it's in. Such situations can cause problems because Grails may guess incorrectly the type of the association. Consider this simple class:
    時々、同じ種類のプロパティを複数持つドメインクラスを作成することがあるでしょう。自己参照を持つ場合さえあります。例えば、関連するプロパティの種類が、自分自身の種類と同じドメインクラスなどです。 そのような状態が問題となる場合があります。これはGrailsが関連の種類を誤って推測するために起こりえます。次のシンプルなクラスについて考えてみましょう:

    class Person {
        String name
        Person parent

    static belongsTo = [ supervisor: Person ]

    static constraints = { supervisor nullable: true } }

    As far as Grails is concerned, the parent and supervisor properties are two directions of the same association. So when you set the parent property on a Person instance, Grails will automatically set the supervisor property on the other Person instance. This may be what you want, but if you look at the class, what we in fact have are two unidirectional relationships.
    Grailsの動作としては、parentプロパティとsupervisorプロパティを2方向の同じ関連として扱います。つまり、PersonインスタンスAのparentプロパティにPersonインスタンスBを格納した時、Grailsは自動的にPersonインスタンスBのsupervisorプロパティにPersonインスタンスAを格納します。 これは期待した動作かもしれません。しかしクラスを見れば、むしろ2つの単方向の関連を持つことを期待するでしょう。

    To guide Grails to the correct mapping, you can tell it that a particular association is unidirectional through the mappedBy property:
    正しいマッピングをGrailsに伝えるために、 mappedByプロパティを使用して特定の関連が単方向であることを示すことができます:

    class Person {
        String name
        Person parent

    static belongsTo = [ supervisor: Person ]

    static mappedBy = [ supervisor: "none", parent: "none" ]

    static constraints = { supervisor nullable: true } }

    You can also replace "none" with any property name of the target class. And of course this works for normal domain classes too, not just self-referential ones. Nor is the mappedBy property limited to many-to-one and one-to-one associations: it also works for one-to-many and many-to-many associations as you'll see in the next section.

    If you have a property called "none" on your domain class, this approach won't work currently! The "none" property will be treated as the reverse direction of the association (or the "back reference"). Fortunately, "none" is not a common domain class property name.
    ドメインクラスに"none"という名前のプロパティがある場合はこの方法は上手く動きません! "none"プロパティは反対方向、あるいは後方への参照として扱われます。 "none"はプロパティ名としては珍しい名前のため、特に気にする必要はないでしょう。 1対多 (One-to-many)

    A one-to-many relationship is when one class, example Author, has many instances of another class, example Book. With Grails you define such a relationship with the hasMany setting:
    1対多の関連は、Authorのような1つのクラス、Bookのような他クラスのインスタンスを複数保持します。 GrailsではhasManyの設定でこの関連を定義します。

    class Author {
        static hasMany = [books: Book]

    String name }

    class Book {
        String title

    In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table.
    この場合は単方向の1対多を持っています。 Grailsはデフォルトでは結合テーブルによって、この種類の関連をマップします。

    The ORM DSL allows mapping unidirectional relationships using a foreign key association instead
    ORM DSLでは代わりに外部キーの参照を使用した単方向関連の設定もできます。

    Grails will automatically inject a property of type java.util.Set into the domain class based on the hasMany setting. This can be used to iterate over the collection:
    GrailsはhasManyを持つドメインクラスにjava.util.Set型のプロパティを自動的に注入します。 このコレクションはイテレートして使えます。

    def a = Author.get(1)

    for (book in a.books) { println book.title }

    The default fetch strategy used by Grails is "lazy", which means that the collection will be lazily initialized on first access. This can lead to the n+1 problem if you are not careful.

    If you need "eager" fetching you can use the ORM DSL or specify eager fetching as part of a query

    Grailsによるデフォルトのフェッチ戦略は"lazy"です。これは最初のアクセスによってコレクションが遅延初期化されること意味します。 この遅延初期化は、注意を怠るとN+1問題を引き起こします。

    もし"eager"フェッチが必要な場合は、ORM DSLを使うか、またはクエリ中で"eager"フェッチを指定してください。

    The default cascading behaviour is to cascade saves and updates, but not deletes unless a belongsTo is also specified:

    class Author {
        static hasMany = [books: Book]

    String name }

    class Book {
        static belongsTo = [author: Author]
        String title

    If you have two properties of the same type on the many side of a one-to-many you have to use mappedBy to specify which the collection is mapped:

    class Airport {
        static hasMany = [flights: Flight]
        static mappedBy = [flights: "departureAirport"]

    class Flight {
        Airport departureAirport
        Airport destinationAirport

    This is also true if you have multiple collections that map to different properties on the many side:

    class Airport {
        static hasMany = [outboundFlights: Flight, inboundFlights: Flight]
        static mappedBy = [outboundFlights: "departureAirport",
                           inboundFlights: "destinationAirport"]

    class Flight {
        Airport departureAirport
        Airport destinationAirport
    } 多対多 (Many-to-many)

    Grails supports many-to-many relationships by defining a hasMany on both sides of the relationship and having a belongsTo on the owned side of the relationship:

    class Book {
        static belongsTo = Author
        static hasMany = [authors:Author]
        String title

    class Author {
        static hasMany = [books:Book]
        String name

    Grails maps a many-to-many using a join table at the database level. The owning side of the relationship, in this case Author, takes responsibility for persisting the relationship and is the only side that can cascade saves across.
    Grailsはデータベースレベルでは結合テーブルを使用して多対多をマップします。 関連の所有する側(この例ではAuthor)は、関連の永続化の責務を持ちます。そして、この所有する側からのみ保存のカスケードが可能です。

    For example this will work and cascade saves:

    new Author(name:"Stephen King")
            .addToBooks(new Book(title:"The Stand"))
            .addToBooks(new Book(title:"The Shining"))

    However this will only save the Book and not the authors!

    new Book(name:"Groovy in Action")
            .addToAuthors(new Author(name:"Dierk Koenig"))
            .addToAuthors(new Author(name:"Guillaume Laforge"))

    This is the expected behaviour as, just like Hibernate, only one side of a many-to-many can take responsibility for managing the relationship.

    Grails' Scaffolding feature does not currently support many-to-many relationship and hence you must write the code to manage the relationship yourself
    Grailsのスカッフォルドは現在、多対多の関連をサポートしていません。 そのため、関連を管理するコードは自分で書かなければなりません。 基本コレクション型

    As well as associations between different domain classes, GORM also supports mapping of basic collection types. For example, the following class creates a nicknames association that is a Set of String instances:
    異なるドメインクラス間の関連に加えて、GORMは基本コレクション型のマッピングもサポートしています。 例えば、以下のクラスはStringSetであるnicknamesの関連を作成します。

    class Person {
        static hasMany = [nicknames: String]

    GORM will map an association like the above using a join table. You can alter various aspects of how the join table is mapped using the joinTable argument:
    GORMでは、上記のような関連は結合テーブルを用いてマップされます。 joinTable引数を使って、どのように結合テーブルにマップされるかを変更できます。

    class Person {

    static hasMany = [nicknames: String]

    static mapping = { hasMany joinTable: [name: 'bunch_o_nicknames', key: 'person_id', column: 'nickname', type: "text"] } }

    The example above will map to a table that looks like the following:

    bunch_o_nicknames Table

    | person_id         |     nickname          |
    |   1               |      Fred             |

    6.2.2 GORMでのコンポジション

    As well as association, Grails supports the notion of composition. In this case instead of mapping classes onto separate tables a class can be "embedded" within the current table. For example:
    関連に加えて、Grailsはコンポジションの概念をサポートしています。 次の場合は、それぞれのドメインクラス毎に別々のテーブルにマッピングされる代わりに、別のドメインクラスのカラムを対象ドメインクラスのテーブルに「埋め込む」ことができます。

    class Person {
        Address homeAddress
        Address workAddress
        static embedded = ['homeAddress', 'workAddress']

    class Address { String number String code }

    The resulting mapping would looking like this:

    If you define the Address class in a separate Groovy file in the grails-app/domain directory you will also get an address table. If you don't want this to happen use Groovy's ability to define multiple classes per file and include the Address class below the Person class in the grails-app/domain/Person.groovy file
    もしgrails-app/domainディレクトリ内に別のGroovyファイルとしてAddressクラスを定義した場合は、以前と同じようにaddressテーブルが作成されてしまいます。 これを避けたい場合は、1ファイルに複数のクラスを定義できるGroovyの能力を使い、grails-app/domain/Person.groovyファイルのPersonクラスの下にAddressクラスを含めてください。

    6.2.3 GORMでの継承

    GORM supports inheritance both from abstract base classes and concrete persistent GORM entities. For example:
    GORMは抽象クラス、または他のGORMエンティティクラスからの継承をサポートしています。 例えば:

    class Content {
         String author

    class BlogEntry extends Content {
        URL url

    class Book extends Content {
        String ISBN

    class PodCast extends Content {
        byte[] audioStream

    In the above example we have a parent Content class and then various child classes with more specific behaviour.



    At the database level Grails by default uses table-per-hierarchy mapping with a discriminator column called class so the parent class (Content) and its subclasses (BlogEntry, Book etc.), share the same table.
    データベースレベルでは、Grailsはデフォルトでclassという名前の識別カラムと共にtable-per-hierarchyマッピングを使います。 これは親クラス(Content)と、その子クラス(BlogEntryBookなど)が同じテーブル上に格納されます。

    Table-per-hierarchy mapping has a down side in that you cannot have non-nullable properties with inheritance mapping. An alternative is to use table-per-subclass which can be enabled with the ORM DSL
    table-per-hierarchyマッピングは継承先のマッピングで非nullableプロパティを持てないという難点があります。 代替手段はtable-per-subclassを使うことです。 これはORM DSLで有効にできます。

    However, excessive use of inheritance and table-per-subclass can result in poor query performance due to the use of outer join queries. In general our advice is if you're going to use inheritance, don't abuse it and don't make your inheritance hierarchy too deep.
    しかし、過度の継承とtable-per-subclassの使用は、外部結合(OUTER JOIN)のせいでクエリ性能が劣化する可能性があります。 一般的なアドバイスとして、もし継承を使うなら、継承を乱用せず、継承階層が深くならないようにしてください。

    Polymorphic Queries


    The upshot of inheritance is that you get the ability to polymorphically query. For example using the list method on the Content super class will return all subclasses of Content:
    継承の結果としてポリモーフィズムを使ったクエリが可能になります。 例えば、親のContentクラス上でlistメソッドを使うと、Contentのすべてのサブクラスが返されます:

    def content = Content.list() // list all blog entries, books and podcasts
    content = Content.findAllByAuthor('Joe Bloggs') // find all by author

    def podCasts = PodCast.list() // list only podcasts

    6.2.4 セット、リスト、マップ

    h4. Sets of Objects


    By default when you define a relationship with GORM it is a java.util.Set which is an unordered collection that cannot contain duplicates. In other words when you have:
    デフォルトでは、GORMを使って関連を定義した場合、java.util.Setになります。 これは、順序を持たないコレクションで、重複要素を含めません。 言い換えると、次のようなドメインクラスがあるとき:

    class Author {
        static hasMany = [books: Book]

    The books property that GORM injects is a java.util.Set. Sets guarantee uniquenes but not order, which may not be what you want. To have custom ordering you configure the Set as a SortedSet:
    GORMが注入するbooksプロパティはjava.util.Setになる、ということです。 セットはユニーク性を保証しますが、順序は保証しません。 これでは都合が悪い場合もあるかもしれません。 独自の順序を持つにはセットをSortedSetに設定します:

    class Author {

    SortedSet books

    static hasMany = [books: Book] }

    In this case a java.util.SortedSet implementation is used which means you must implement java.lang.Comparable in your Book class:
    この場合は、java.util.SortedSetの実装が使われます。 これは、Bookクラスでjava.lang.Comparableを実装しなければならないことを意味します:

    class Book implements Comparable {

    String title Date releaseDate = new Date()

    int compareTo(obj) { releaseDate.compareTo(obj.releaseDate) } }

    The result of the above class is that the Book instances in the books collection of the Author class will be ordered by their release date.

    Lists of Objects


    To keep objects in the order which they were added and to be able to reference them by index like an array you can define your collection type as a List:

    class Author {

    List books

    static hasMany = [books: Book] }

    In this case when you add new elements to the books collection the order is retained in a sequential list indexed from 0 so you can do:
    この場合は、新しい要素をbooksコレクションへ追加したときに、0からインデックスが付与された一連のリストとして、順序が保持されます。 そして、次のようにアクセスできます:

    author.books[0] // get the first book

    The way this works at the database level is Hibernate creates a books_idx column where it saves the index of the elements in the collection to retain this order at the database level.

    When using a List, elements must be added to the collection before being saved, otherwise Hibernate will throw an exception (org.hibernate.HibernateException: null index column for collection):
    Listを使った場合、要素は保存前にコレクションへ追加されなければなりません。 コレクション追加前に単体で保存されてしまっていると、Hibernateが例外をスローします(org.hibernate.HibernateException: コレクションのインデックスカラムがnull)。

    // This won't work!
    def book = new Book(title: 'The Shining')

    // Do it this way instead. def book = new Book(title: 'Misery') author.addToBooks(book) author.save()

    h4. Bags of Objects


    If ordering and uniqueness aren't a concern (or if you manage these explicitly) then you can use the Hibernate Bag type to represent mapped collections.


    The only change required for this is to define the collection type as a Collection:

    class Author {

    Collection books

    static hasMany = [books: Book] }

    Since uniqueness and order aren't managed by Hibernate, adding to or removing from collections mapped as a Bag don't trigger a load of all existing instances from the database, so this approach will perform better and require less memory than using a Set or a List.

    h4. Maps of Objects


    If you want a simple map of string/value pairs GORM can map this with the following:

    class Author {
        Map books // map of ISBN:book names

    def a = new Author() a.books = ["1590597583":"Grails Book"] a.save()

    In this case the key and value of the map MUST be strings.
    このケースでは、 キーと値は必ず文字列である必要があります。

    If you want a Map of objects then you can do this:

    class Book {

    Map authors

    static hasMany = [authors: Author] }

    def a = new Author(name:"Stephen King")

    def book = new Book() book.authors = [stephen:a] book.save()

    The static hasMany property defines the type of the elements within the Map. The keys for the map must be strings.

    A Note on Collection Types and Performance


    The Java Set type doesn't allow duplicates. To ensure uniqueness when adding an entry to a Set association Hibernate has to load the entire associations from the database. If you have a large numbers of entries in the association this can be costly in terms of performance.
    JavaのSet型は重複を許容しません。 Setの関連へエントリを追加するときに、ユニーク性を保証するため、Hibernateはデータベースからすべての関連を読み込まなければなりません。 もし関連のエントリの数が大量の場合、パフォーマンスの点でコストがかかりすぎる可能性があります。

    The same behavior is required for List types, since Hibernate needs to load the entire association to maintain order. Therefore it is recommended that if you anticipate a large numbers of records in the association that you make the association bidirectional so that the link can be created on the inverse side. For example consider the following code:
    同じ振る舞いがList型でも必要になります。 これは、Hibernateがすべての関連の順序を保持するため、事前にすべての関連を読み込む必要があるからです。 そのため、事前に関連エントリが大量になることがわかっている場合は、双方向関連にして、反対側から関連を作成することをお勧めします。 たとえば、以下のコードを考えてみます:

    def book = new Book(title:"New Grails Book")
    def author = Author.get(1)
    book.author = author

    In this example the association link is being created by the child (Book) and hence it is not necessary to manipulate the collection directly resulting in fewer queries and more efficient code. Given an Author with a large number of associated Book instances if you were to write code like the following you would see an impact on performance:
    この例では、関連は子(Book)によって作成されます。 このようにすることで、直接コレクションを操作する必要がなくなるため、より少ないクエリで効率的なコードとなります。 Authorと関連する大量のBookインスタンスが与えられたとき、下のようなコードを書いてしまうとパフォーマンスに重大な影響があります:

    def book = new Book(title:"New Grails Book")
    def author = Author.get(1)

    You could also model the collection as a Hibernate Bag as described above.

    6.3 永続化の基礎

    A key thing to remember about Grails is that under the surface Grails is using Hibernate for persistence. If you are coming from a background of using ActiveRecord or iBatis/MyBatis, Hibernate's "session" model may feel a little strange.
    Grailsでは、永続化実現のためにHibernate が使われています。Hibernateは「セッション」という概念を採用していますが、この概念はActiveRecordiBatis/MyBatisに慣れ親しんでいる人にとっては、少し不可解に感じるかも知れません。

    Grails automatically binds a Hibernate session to the currently executing request. This lets you use the save and delete methods as well as other GORM methods transparently.

    h4. Transactional Write-Behind


    A useful feature of Hibernate over direct JDBC calls and even other frameworks is that when you call save or delete it does not necessarily perform any SQL operations at that point. Hibernate batches up SQL statements and executes them as late as possible, often at the end of the request when flushing and closing the session. This is typically done for you automatically by Grails, which manages your Hibernate session.
    Hibernateは、直接JDBC APIを呼び出す方法や、他のフレームワークを使う方法と比べて便利な特徴を備えています。具体的にはsaveメソッドやdeleteメソッドを呼び出した瞬間にはSQLを発行せず、できる限り後ろで、まとめて発行しようとします。セッションがフラッシュ、またはクローズされるまでSQLが発行されないことも珍しくありません。なお、通常では、これらの動作はHibernateのセッションを管理しているGrailsによって自動的に行われます。

    Hibernate caches database updates where possible, only actually pushing the changes when it knows that a flush is required, or when a flush is triggered programmatically. One common case where Hibernate will flush cached updates is when performing queries since the cached information might be included in the query results. But as long as you're doing non-conflicting saves, updates, and deletes, they'll be batched until the session is flushed. This can be a significant performance boost for applications that do a lot of database writes.

    Note that flushing is not the same as committing a transaction. If your actions are performed in the context of a transaction, flushing will execute SQL updates but the database will save the changes in its transaction queue and only finalize the updates when the transaction commits.

    6.3.1 保存と更新

    An example of using the save method can be seen below:

    def p = Person.get(1)

    This save will be not be pushed to the database immediately - it will be pushed when the next flush occurs. But there are occasions when you want to control when those statements are executed or, in Hibernate terminology, when the session is "flushed". To do so you can use the flush argument to the save method:

    def p = Person.get(1)
    p.save(flush: true)

    Note that in this case all pending SQL statements including previous saves, deletes, etc. will be synchronized with the database. This also lets you catch any exceptions, which is typically useful in highly concurrent scenarios involving optimistic locking:
    この形式のsaveメソッドの呼び出しによって、保留されていた 全て のSQL(以前にflush指定なしに呼び出されたsaveメソッドやdeleteメソッドを含む)が発行され、データベースと同期することになります。 SQL発行に伴い発生する可能性のある例外は、このタイミングで必要に応じてキャッチしてください。たとえば、楽観的ロック利用時に競合が発生した場合の例外は、ここでキャッチします。

    def p = Person.get(1)
    try {
        p.save(flush: true)
    catch (org.springframework.dao.DataIntegrityViolationException e) {
        // deal with exception

    Another thing to bear in mind is that Grails validates a domain instance every time you save it. If that validation fails the domain instance will not be persisted to the database. By default, save() will simply return null in this case, but if you would prefer it to throw an exception you can use the failOnError argument:
    saveメソッドに関して、もうひとつ注意すべきことがあります。ドメインインスタンスはsaveされる度にバリデーションが実行されますが、バリデーションに失敗した場合は、データベースへの反映は 行われません 。 バリデーションに失敗したとき、save()メソッドは、デフォルトではnullを返します。例外を発生させたい場合には、名前付き引数failOnErrorを使って、以下のようにしてください:

    def p = Person.get(1)
    try {
        p.save(failOnError: true)
    catch (ValidationException e) {
        // deal with exception

    You can even change the default behaviour with a setting in Config.groovy, as described in the section on configuration. Just remember that when you are saving domain instances that have been bound with data provided by the user, the likelihood of validation exceptions is quite high and you won't want those exceptions propagating to the end user.

    You can find out more about the subtleties of saving data in this article - a must read!

    6.3.2 オブジェクトの削除

    An example of the delete method can be seen below:

    def p = Person.get(1)

    As with saves, Hibernate will use transactional write-behind to perform the delete; to perform the delete in-place you can use the flush argument:

    def p = Person.get(1)
    p.delete(flush: true)

    Using the flush argument lets you catch any errors that occur during a delete. A common error that may occur is if you violate a database constraint, although this is normally down to a programming or schema error. The following example shows how to catch a DataIntegrityViolationException that is thrown when you violate the database constraints:
    flush引数を使うことによって、削除にともなって発生する可能性のあるエラーに対処する必要が出てきます。 このタイミングで発生する、よくあるエラーの1つに、データベースの制約違反があります。 このエラーは、プログラミングやデータベーススキーマの間違いに起因することが多いのですが、その時に発生する例外DataIntegrityViolationExceptionをキャッチする例を以下に示します:

    def p = Person.get(1)

    try { p.delete(flush: true) } catch (org.springframework.dao.DataIntegrityViolationException e) { flash.message = "Could not delete person ${p.name}" redirect(action: "show", id: p.id) }

    Note that Grails does not supply a deleteAll method as deleting data is discouraged and can often be avoided through boolean flags/logic.

    If you really need to batch delete data you can use the executeUpdate method to do batch DML statements:

    Customer.executeUpdate("delete Customer c where c.name = :oldName",
                           [oldName: "Fred"])

    6.3.3 カスケード更新削除を理解する

    It is critical that you understand how cascading updates and deletes work when using GORM. The key part to remember is the belongsTo setting which controls which class "owns" a relationship.

    Whether it is a one-to-one, one-to-many or many-to-many, defining belongsTo will result in updates cascading from the owning class to its dependant (the other side of the relationship), and for many-/one-to-one and one-to-many relationships deletes will also cascade.

    If you do not define belongsTo then no cascades will happen and you will have to manually save each object (except in the case of the one-to-many, in which case saves will cascade automatically if a new instance is in a hasMany collection).
    belongsToを定義 しない 場合はカスケードしないため、関連するオブジェクトを1つ1つsaveしなければなりません(ただし、1対多の場合だけは例外です。このケースではhasMenyコレクション内に新しいインスタンスが有れば保存が自動的にカスケードします)。

    Here is an example:

    class Airport {
        String name
        static hasMany = [flights: Flight]

    class Flight {
        String number
        static belongsTo = [airport: Airport]

    If I now create an Airport and add some Flights to it I can save the Airport and have the updates cascaded down to each flight, hence saving the whole object graph:

    new Airport(name: "Gatwick")
            .addToFlights(new Flight(number: "BA3430"))
            .addToFlights(new Flight(number: "EZ0938"))

    Conversely if I later delete the Airport all Flights associated with it will also be deleted:

    def airport = Airport.findByName("Gatwick")

    However, if I were to remove belongsTo then the above cascading deletion code would not work. To understand this better take a look at the summaries below that describe the default behaviour of GORM with regards to specific associations. Also read part 2 of the GORM Gotchas series of articles to get a deeper understanding of relationships and cascading.
    ところが、belongsTo の定義が削除されている状態で、上記に記載した削除のコードを実行した場合は、カスケード削除は動作しません。以降では、この事象をより良く理解できるように、それぞれの関連に対するGORMのデフォルトの振る舞いを説明します。 関連とカスケードについて、更に深く理解したい場合には、GORM Gotchas (Part 2)も参照してください。

    h5. Bidirectional one-to-many with belongsTo

    class A { static hasMany = [bees: B] }

    class B { static belongsTo = [a: A] }

    In the case of a bidirectional one-to-many where the many side defines a belongsTo then the cascade strategy is set to "ALL" for the one side and "NONE" for the many side.

    h5. Unidirectional one-to-many

    class A { static hasMany = [bees: B] }

    class B {  }

    In the case of a unidirectional one-to-many where the many side defines no belongsTo then the cascade strategy is set to "SAVE-UPDATE".

    h5. Bidirectional one-to-many, no belongsTo

    class A { static hasMany = [bees: B] }

    class B { A a }

    In the case of a bidirectional one-to-many where the many side does not define a belongsTo then the cascade strategy is set to "SAVE-UPDATE" for the one side and "NONE" for the many side.

    h5. Unidirectional one-to-one with belongsTo

    class A {  }

    class B { static belongsTo = [a: A] }

    In the case of a unidirectional one-to-one association that defines a belongsTo then the cascade strategy is set to "ALL" for the owning side of the relationship (A->B) and "NONE" from the side that defines the belongsTo (B->A)

    Note that if you need further control over cascading behaviour, you can use the ORM DSL.
    なお、カスケードの振る舞いについて、ここに書かれている内容を超える制御が必要な場合は、ORM DSLを利用してください。

    6.3.4 EagerフェッチとLazyフェッチ

    Associations in GORM are by default lazy. This is best explained by example:

    class Airport {
        String name
        static hasMany = [flights: Flight]

    class Flight {
        String number
        Location destination
        static belongsTo = [airport: Airport]

    class Location {
        String city
        String country

    Given the above domain classes and the following code:

    def airport = Airport.findByName("Gatwick")
    for (flight in airport.flights) {
        println flight.destination.city

    GORM will execute a single SQL query to fetch the Airport instance, another to get its flights, and then 1 extra query for each iteration over the flights association to get the current flight's destination. In other words you get N+1 queries (if you exclude the original one to get the airport).
    このコードを実行すると、GORMは、まず、Airportインスタンスを取得するためのSQLを発行します。 次に、airport.flightsにアクセスしようとして、そのAirportが所有しているFlightインスタンスの集合を取得するためのSQLを発行します。 それから、 airport.flights内に格納されている各Flightインスタンスについて、そのフライトのdestinationを取得するために、 それぞれ 1回のSQLを発行します。以上をまとめると、上記コード実行のために N+1 回のクエリーが発行されることになります(初回のAirportインスタンスを取得するためのクエリーを除く)。

    h3. Configuring Eager Fetching


    An alternative approach that avoids the N+1 queries is to use eager fetching, which can be specified as follows:
    N+1 回のクエリーが発行されてしまうことを回避するためのアプローチの1つに、eagerフェッチングがあります。eagerフェッチングを使うには、以下のように指定します:

    class Airport {
        String name
        static hasMany = [flights: Flight]
        static mapping = {
            flights lazy: false

    In this case the flights association will be loaded at the same time as its Airport instance, although a second query will be executed to fetch the collection. You can also use fetch: 'join' instead of lazy: false , in which case GORM will only execute a single query to get the airports and their flights. This works well for single-ended associations, but you need to be careful with one-to-manys. Queries will work as you'd expect right up to the moment you add a limit to the number of results you want. At that point, you will likely end up with fewer results than you were expecting. The reason for this is quite technical but ultimately the problem arises from GORM using a left outer join.
    このようにすることで、Airportインスタンスを取得する時に、同時に、関連しているflightsも取得するようになりますが、それぞれ別のクエリーが発行される点は変わりません。lazy: falseの代わりにfetch: 'join'を使うと、1回のクエリーで、Airportインスタンスと、それに関連するflightsを取得するようになります。ところが、fetch: 'join'を使う方法は、単一端関連ではうまく動作するのですが、この例のような1対多の関連に適用する場合には注意が必要です。具体的には、取得するレコード数に上限(limit)を指定しなければ、クエリーは問題なく動作するものの、上限を指定すると、本来返されるべき数よりも少ないレコードしか取得できないという事象が発生してしまいます。このようなことが発生する理由は技術的なもので、GORMが、この機能を実現するためにleft outer joinを使っていることに起因します。

    So, the recommendation is currently to use fetch: 'join' for single-ended associations and lazy: false for one-to-manys.
    以上の理由により、現時点では、単一端関連ではfetch: 'join'を、1対多関連ではlazy: falseを使うことを推奨します。

    Be careful how and where you use eager loading because you could load your entire database into memory with too many eager associations. You can find more information on the mapping options in the section on the ORM DSL.
    あまりに多くの関連をeagerフェッチングとしてしまうと、データベース全体がメモリにロードされてしまう可能性があるため、eagerフェッチングを採用する場合は、使うべき場所と方法について十分に注意するようにしてください。mappingに指定できるオプションについての詳しい情報はORM DSLの章に記載されています。

    h3. Using Batch Fetching


    Although eager fetching is appropriate for some cases, it is not always desirable. If you made everything eager you could quite possibly load your entire database into memory resulting in performance and memory problems. An alternative to eager fetching is to use batch fetching. You can configure Hibernate to lazily fetch results in "batches". For example:
    eagerフェッチングが適切なケースはもちろん有りますが、常に最適なわけではありません。 たとえば、全てをeagerフェッチングにしてしまうと、データベース全体がメモリにロードされ、性能問題やメモリ不足の問題が発生するでしょう。そこで、eagerフェッチングに代わるもう1つの選択肢として一括フェッチングが用意されています。一括フェッチングでは、あるまとまった複数のレコードを1単位として、lazyフェッチングするように設定することができます。以下に例を示します:

    class Airport {
        String name
        static hasMany = [flights: Flight]
        static mapping = {
            flights batchSize: 10

    In this case, due to the batchSize argument, when you iterate over the flights association, Hibernate will fetch results in batches of 10. For example if you had an Airport that had 30 flights, if you didn't configure batch fetching you would get 1 query to fetch the Airport and then 30 queries to fetch each flight. With batch fetching you get 1 query to fetch the Airport and 3 queries to fetch each Flight in batches of 10. In other words, batch fetching is an optimization of the lazy fetching strategy. Batch fetching can also be configured at the class level as follows:

    class Flight {
        static mapping = {
            batchSize 10

    Check out part 3 of the GORM Gotchas series for more in-depth coverage of this tricky topic.
    この部分について、より深く、網羅的な知識が必要な場合には、GORM Gotchas (Part 3)の記事を参照してください。

    6.3.5 悲観的ロックと楽観的ロック

    h4. Optimistic Locking


    By default GORM classes are configured for optimistic locking. Optimistic locking is a feature of Hibernate which involves storing a version value in a special version column in the database that is incremented after each update.
    GORMでは、デフォルトで、各ドメインクラスは楽観的ロックを使うように設定されています。 楽観的ロックは、Hibernateが備えている機能の1つです。 データベース上の専用のversionカラムにバージョン番号を格納して、レコードを更新する度に値をインクリメントします。

    The version column gets read into a version property that contains the current versioned state of persistent instance which you can access:
    versionカラムは、永続化済みのドメインクラスインスタンスのversionプロパティとして読み込まれます。 このプロパティを使って、データベースから取得した時点のバージョン番号を取得できます。 以下にコード例を示します:

    def airport = Airport.get(10)

    println airport.version

    When you perform updates Hibernate will automatically check the version property against the version column in the database and if they differ will throw a StaleObjectException. This will roll back the transaction if one is active.
    データベースを更新するときには、Hibernateは自動的に、データベースのversionカラムに格納されている値と、更新対象のインスタンスが保持しているversionプロパティの値を比較します。 そして、2つの値が異なる場合にはStaleObjectException例外をスローします。 トランザクションが有効な場合は、この例外発生によって、トランザクションもロールバックします。

    This is useful as it allows a certain level of atomicity without resorting to pessimistic locking that has an inherit performance penalty. The downside is that you have to deal with this exception if you have highly concurrent writes. This requires flushing the session:
    この方法は、本質的に性能上の問題をかかえている悲観的ロックに頼らずとも、ある水準の原子性を保証することができる点が便利ですが、一方で短所も存在します。 それは、実際に並行に更新が発生してしまった場合に、開発者が明示的に例外処理しなければならいという点です。 そして、この例外処理のためにはセッションのフラッシュが必要になります:

    def airport = Airport.get(10)

    try { airport.name = "Heathrow" airport.save(flush: true) } catch (org.springframework.dao.OptimisticLockingFailureException e) { // deal with exception }

    The way you deal with the exception depends on the application. You could attempt a programmatic merge of the data or go back to the user and ask them to resolve the conflict.
    この例外が発生した時にどのように振る舞うべきかは、アプリケーションの要件に依存します。 たとえば、競合が発生したデータを機械的にマージする、エンドユーザに競合を解決するように頼む、などの振る舞いが考えられるでしょう。

    Alternatively, if it becomes a problem you can resort to pessimistic locking.
    あるいは、そのような振る舞いをすることが問題になることもあるでしょう。 そのときは最後の手段として、悲観的ロックを使うこともできます。

    The version will only be updated after flushing the session.

    h4. Pessimistic Locking


    Pessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row in the database. This has the implication that other read operations will be blocking until the lock is released.
    悲観的ロックの利用は、"SELECT * FOR UPDATE" というSQL文を発行して、データベースの行をロックすることに相当します。 そのため、行ロックがリリースされるまでは、他の読み取り操作もブロックされてしまいます。

    In Grails pessimistic locking is performed on an existing instance with the lock method:

    def airport = Airport.get(10)
    airport.lock() // lock for update
    airport.name = "Heathrow"

    Grails will automatically deal with releasing the lock for you once the transaction has been committed. However, in the above case what we are doing is "upgrading" from a regular SELECT to a SELECT..FOR UPDATE and another thread could still have updated the record in between the call to get() and the call to lock().
    このようにして獲得したロックは、トランザクションがコミットされたタイミングで、Grailsによって自動的にリリースされます。 ただし、この方法は、通常のSELECT文で一旦レコードを取得した後に、SELECT..FOR UPDATE文で取得し直すことになってしまうことに注意してください。 そのため、get()メソッドを呼び出してからlock()メソッドを呼び出す間に、他のスレッドがレコードを更新する可能性が残ってしまいます。

    To get around this problem you can use the static lock method that takes an id just like get:

    def airport = Airport.lock(10) // lock for update
    airport.name = "Heathrow"

    In this case only SELECT..FOR UPDATE is issued.
    この方法を使えば、SELECT..FOR UPDATE文だけが発行されるので、最初の方法のような問題は発生しません。

    As well as the lock method you can also obtain a pessimistic locking using queries. For example using a dynamic finder:
    lockメソッドを使う方法以外に、クエリで悲観的ロックを使う方法もあります。 たとえば、ダイナミックファインダを使う場合は:

    def airport = Airport.findByName("Heathrow", [lock: true])

    Or using criteria:

    def airport = Airport.createCriteria().get {
        eq('name', 'Heathrow')
        lock true

    6.3.6 変更確認

    Once you have loaded and possibly modified a persistent domain class instance, it isn't straightforward to retrieve the original values. If you try to reload the instance using get Hibernate will return the current modified instance from its Session cache. Reloading using another query would trigger a flush which could cause problems if your data isn't ready to be flushed yet. So GORM provides some methods to retrieve the original values that Hibernate caches when it loads the instance (which it uses for dirty checking).
    永続化されたドメインクラスのインスタンスを読み込み、いったん変更を加えると、簡単に元の値を取り出すことはできません。 もし、getを使ってインスタンスを再読み込みしようとすると、Hibernateはセッションのキャッシュから現在変更を加えたインスタンスを返します。 まだデータがフラッシュできる状態でない場合、他のクエリを使って再読み込みをしようとすると、データがフラッシュできる状態でないにもかかわらずフラッシュが行われ問題を引き起こします。 GORMは、Hibernateがインスタンスの読み込み時にキャッシュする値(このインスタンスはdirtyチェックに使われる)を取り出すいくつかのメソッドを提供します。

    h4. isDirty


    You can use the isDirty method to check if any field has been modified:

    def airport = Airport.get(10)
    assert !airport.isDirty()

    airport.properties = params if (airport.isDirty()) { // do something based on changed state }

    isDirty() does not currently check collection associations, but it does check all other persistent properties and associations.
    isDirty()は、今のところ関連のコレクションをチェックしません。 しかし、他のすべての永続化プロパティと関連をチェックします。

    You can also check if individual fields have been modified:

    def airport = Airport.get(10)
    assert !airport.isDirty()

    airport.properties = params if (airport.isDirty('name')) { // do something based on changed name }

    h4. getDirtyPropertyNames


    You can use the getDirtyPropertyNames method to retrieve the names of modified fields; this may be empty but will not be null:
    変更されたフィールドの名前を取得するにはgetDirtyPropertyNamesメソッドを使います。 このメソッドは空リストを返すかもしれませんが、nullを返すことはありません:

    def airport = Airport.get(10)
    assert !airport.isDirty()

    airport.properties = params def modifiedFieldNames = airport.getDirtyPropertyNames() for (fieldName in modifiedFieldNames) { // do something based on changed value }

    h4. getPersistentValue


    You can use the getPersistentValue method to retrieve the value of a modified field:

    def airport = Airport.get(10)
    assert !airport.isDirty()

    airport.properties = params def modifiedFieldNames = airport.getDirtyPropertyNames() for (fieldName in modifiedFieldNames) { def currentValue = airport."$fieldName" def originalValue = airport.getPersistentValue(fieldName) if (currentValue != originalValue) { // do something based on changed value } }

    6.4 GORMでのクエリー

    GORM supports a number of powerful ways to query from dynamic finders, to criteria to Hibernate's object oriented query language HQL. Depending on the complexity of the query you have the following options in order of flexibility and power:

    • Dynamic Finders
    • Where Queries
    • Criteria Queries
    • Hibernate Query Language (HQL)

    • ダイナミックファインダー
    • Whereクエリー
    • クライテリアクエリー
    • Hibernateクエリー言語 (HQL)

    In addition, Groovy's ability to manipulate collections with GPath and methods like sort, findAll and so on combined with GORM results in a powerful combination.
    さらに、Groovyの機能であるコレクション操作機能 GPath と、GORMの持つsortやfindAllなどのメソッドの組み合わせは、すばらしい結果をもたらします。

    However, let's start with the basics.

    h4. Listing instances


    Use the list method to obtain all instances of a given class:

    def books = Book.list()

    The list method supports arguments to perform pagination:

    def books = Book.list(offset:10, max:20)

    as well as sorting:

    def books = Book.list(sort:"title", order:"asc")

    Here, the sort argument is the name of the domain class property that you wish to sort on, and the order argument is either asc for ascending or desc for descending.

    h4. Retrieval by Database Identifier


    The second basic form of retrieval is by database identifier using the get method:

    def book = Book.get(23)

    You can also obtain a list of instances for a set of identifiers using getAll:

    def books = Book.getAll(23, 93, 81)

    6.4.1 ダイナミックファインダー

    GORM supports the concept of dynamic finders. A dynamic finder looks like a static method invocation, but the methods themselves don't actually exist in any form at the code level.

    Instead, a method is auto-magically generated using code synthesis at runtime, based on the properties of a given class. Take for example the Book class:

    class Book {
        String title
        Date releaseDate
        Author author

    class Author {
        String name

    The Book class has properties such as title, releaseDate and author. These can be used by the findBy and findAllBy methods in the form of "method expressions":

    def book = Book.findByTitle("The Stand")

    book = Book.findByTitleLike("Harry Pot%")

    book = Book.findByReleaseDateBetween(firstDate, secondDate)

    book = Book.findByReleaseDateGreaterThan(someDate)

    book = Book.findByTitleLikeOrReleaseDateLessThan("%Something%", someDate)

    h4. Method Expressions


    A method expression in GORM is made up of the prefix such as findBy followed by an expression that combines one or more properties. The basic form is:

    Book.findBy([Property][Comparator][Boolean Operator])?[Property][Comparator]

    The tokens marked with a '?' are optional. Each comparator changes the nature of the query. For example:
    '?' 以降はオプションとなります。比較演算子によって、自然な文体でクエリーを書く事が出来るようになります。以下はその例です。:

    def book = Book.findByTitle("The Stand")

    book = Book.findByTitleLike("Harry Pot%")

    In the above example the first query is equivalent to equality whilst the latter, due to the Like comparator, is equivalent to a SQL like expression.

    The possible comparators include:

    • InList - In the list of given values
    • LessThan - less than a given value
    • LessThanEquals - less than or equal a give value
    • GreaterThan - greater than a given value
    • GreaterThanEquals - greater than or equal a given value
    • Like - Equivalent to a SQL like expression
    • Ilike - Similar to a Like, except case insensitive
    • NotEqual - Negates equality
    • InRange - Between the from and to values of a Groovy Range
    • Rlike - Performs a Regexp LIKE in MySQL or Oracle otherwise falls back to Like
    • Between - Between two values (requires two arguments)
    • IsNotNull - Not a null value (doesn't take an argument)
    • IsNull - Is a null value (doesn't take an argument)

    • InList - パラメータの値のリストのいずれかに一致する
    • LessThan - パラメータの値よりも小さい
    • LessThanEquals - パラメータの値より小さいか、等しい
    • GreaterThan - パラメータの値より大きい
    • GreaterThanEquals - パラメータの値より大きいか、等しい
    • Like - SQL文の Like句と同様
    • Ilike - 上のLikeの同類だが、アルファベットの大文字と小文字の差を無視する
    • NotEqual - パラメータの値と等しくない
    • InRange - Between the from and to values of a Groovy Range
    • Rlike - Performs a Regexp LIKE in MySQL or Oracle otherwise falls back to Like
    • Between - 2つの値の範囲内である (2つのパラメータが必要)
    • IsNotNull - Nullではない (パラメータ不要)
    • IsNull - Nullである (パラメータ不要)

    Notice that the last three require different numbers of method arguments compared to the rest, as demonstrated in the following example:
    最後の3つのメソッドの引数の数が、他のメソッドと違うのに気が付きましたか? 以下にサンプルコードを示します。:

    def now = new Date()
    def lastWeek = now - 7
    def book = Book.findByReleaseDateBetween(lastWeek, now)

    books = Book.findAllByReleaseDateIsNull() books = Book.findAllByReleaseDateIsNotNull()

    h4. Boolean logic (AND/OR)


    Method expressions can also use a boolean operator to combine two or more criteria:

    def books = Book.findAllByTitleLikeAndReleaseDateGreaterThan(
                          "%Java%", new Date() - 30)

    In this case we're using And in the middle of the query to make sure both conditions are satisfied, but you could equally use Or:

    def books = Book.findAllByTitleLikeOrReleaseDateGreaterThan(
                          "%Java%", new Date() - 30)

    You can combine as many criteria as you like, but they must all be combined with And or all Or. If you need to combine And and Or or if the number of criteria creates a very long method name, just convert the query to a Criteria or HQL query.

    h4. Querying Associations


    Associations can also be used within queries:

    def author = Author.findByName("Stephen King")

    def books = author ? Book.findAllByAuthor(author) : []

    In this case if the Author instance is not null we use it in a query to obtain all the Book instances for the given Author.

    h4. Pagination and Sorting


    The same pagination and sorting parameters available on the list method can also be used with dynamic finders by supplying a map as the final parameter:

    def books = Book.findAllByTitleLike("Harry Pot%",
                   [max: 3, offset: 2, sort: "title", order: "desc"])

    6.4.2 Whereクエリー

    The where method, introduced in Grails 2.0, builds on the support for Detached Criteria by providing an enhanced, compile-time checked query DSL for common queries. The where method is more flexible than dynamic finders, less verbose than criteria and provides a powerful mechanism to compose queries.
    Grails 2.0から実装されたwhereメソッドはDetached Criteriaの拡張であり、コンパイル時に型チェックなどを実施することが出来るDSLクエリー言語を実現しています。また、whereメソッドはダイナミックファインダーより柔軟で、クライテリアよりは冗長ではないクエリー作成のメカニズムを提供します。

    h4. Basic Querying


    The where method accepts a closure that looks very similar to Groovy's regular collection methods. The closure should define the logical criteria in regular Groovy syntax, for example:

    def query = Person.where {
       firstName == "Bart"
    Person bart = query.find()

    The returned object is a DetachedCriteria instance, which means it is not associated with any particular database connection or session. This means you can use the where method to define common queries at the class level:

    class Person {
        static simpsons = where {
             lastName == "Simpson"
    Person.simpsons.each {
        println it.firstname

    Query execution is lazy and only happens upon usage of the DetachedCriteria instance. If you want to execute a where-style query immediately there are variations of the findAll and find methods to accomplish this:

    def results = Person.findAll {
         lastName == "Simpson"
    def results = Person.findAll(sort:"firstName") {
         lastName == "Simpson"
    Person p = Person.find { firstName == "Bart" }

    Each Groovy operator maps onto a regular criteria method. The following table provides a map of Groovy operators to methods:

    OperatorCriteria MethodDescription
    ==eqEqual to
    !=neNot equal to
    >gtGreater than
    <ltLess than
    >=geGreater than or equal to
    <=leLess than or equal to
    ininListContained within the given list
    ==~likeLike a given string
    =~ilikeCase insensitive like

    It is possible use regular Groovy comparison operators and logic to formulate complex queries:

    def query = Person.where {
        (lastName != "Simpson" && firstName != "Fred") || (firstName == "Bart" && age > 9)
    def results = query.list(sort:"firstName")

    The Groovy regex matching operators map onto like and ilike queries unless the expression on the right hand side is a Pattern object, in which case they map onto an rlike query:

    def query = Person.where {
         firstName ==~ ~/B.+/

    Note that rlike queries are only supported if the underlying database supports regular expressions

    A between criteria query can be done by combining the in keyword with a range:

    def query = Person.where {
         age in 18..65

    Finally, you can do isNull and isNotNull style queries by using null with regular comparison operators:

    def query = Person.where {
         middleName == null

    h4. Query Composition


    Since the return value of the where method is a DetachedCriteria instance you can compose new queries from the original query:

    def query = Person.where {
         lastName == "Simpson"
    def bartQuery = query.where {
         firstName == "Bart"
    Person p = bartQuery.find()

    Note that you cannot pass a closure defined as a variable into the where method unless it has been explicitly cast to a DetachedCriteria instance. In other words the following will produce an error:

    def callable = {
        lastName == "Simpson"
    def query = Person.where(callable)

    The above must be written as follows:

    import grails.gorm.DetachedCriteria

    def callable = { lastName == "Simpson" } as DetachedCriteria<Person> def query = Person.where(callable)

    As you can see the closure definition is cast (using the Groovy as keyword) to a DetachedCriteria instance targeted at the Person class.

    h4. Conjunction, Disjunction and Negation


    As mentioned previously you can combine regular Groovy logical operators (|| and &&) to form conjunctions and disjunctions:

    def query = Person.where {
        (lastName != "Simpson" && firstName != "Fred") || (firstName == "Bart" && age > 9)

    You can also negate a logical comparison using !:

    def query = Person.where {
        firstName == "Fred" && !(lastName == 'Simpson')

    h4. Property Comparison Queries


    If you use a property name on both the left hand and right side of a comparison expression then the appropriate property comparison criteria is automatically used:

    def query = Person.where {
       firstName == lastName

    The following table described how each comparison operator maps onto each criteria property comparison method:

    OperatorCriteria MethodDescription
    ==eqPropertyEqual to
    !=nePropertyNot equal to
    >gtPropertyGreater than
    <ltPropertyLess than
    >=gePropertyGreater than or equal to
    <=lePropertyLess than or equal to


    h4. Querying Associations


    Associations can be queried by using the dot operator to specify the property name of the association to be queried:

    def query = Pet.where {
        owner.firstName == "Joe" || owner.firstName == "Fred"

    You can group multiple criterion inside a closure method call where the name of the method matches the association name:

    def query = Person.where {
        pets { name == "Jack" || name == "Joe" }

    This technique can be combined with other top-level criteria:

    def query = Person.where {
         pets { name == "Jack" } || firstName == "Ed"

    For collection associations it is possible to apply queries to the size of the collection:

    def query = Person.where {
           pets.size() == 2

    The following table shows which operator maps onto which criteria method for each size() comparison:

    OperatorCriteria MethodDescription
    ==sizeEqThe collection size is equal to
    !=sizeNeThe collection size is not equal to
    >sizeGtThe collection size is greater than
    <sizeLtThe collection size is less than
    >=sizeGeThe collection size is greater than or equal to
    <=sizeLeThe collection size is less than or equal to


    h4. Subqueries


    It is possible to execute subqueries within where queries. For example to find all the people older than the average age the following query can be used:

    final query = Person.where {
      age > avg(age)

    The following table lists the possible subqueries:

    avgThe average of all values
    sumThe sum of all values
    maxThe maximum value
    minThe minimum value
    countThe count of all values
    propertyRetrieves a property of the resulting entities


    You can apply additional criteria to any subquery by using the of method and passing in a closure containing the criteria:

    def query = Person.where {
      age > avg(age).of { lastName == "Simpson" } && firstName == "Homer"

    Since the property subquery returns multiple results, the criterion used compares all results. For example the following query will find all people younger than people with the surname "Simpson":

    Person.where {
        age < property(age).of { lastName == "Simpson" }

    h4. Other Functions


    There are several functions available to you within the context of a query. These are summarized in the table below:

    secondThe second of a date property
    minuteThe minute of a date property
    hourThe hour of a date property
    dayThe day of the month of a date property
    monthThe month of a date property
    yearThe year of a date property
    lowerConverts a string property to upper case
    upperConverts a string property to lower case
    lengthThe length of a string property
    trimTrims a string property


    Currently functions can only be applied to properties or associations of domain classes. You cannot, for example, use a function on a result of a subquery.

    For example the following query can be used to find all pet's born in 2011:

    def query = Pet.where {
        year(birthDate) == 2011

    You can also apply functions to associations:

    def query = Person.where {
        year(pets.birthDate) == 2009

    h4. Batch Updates and Deletes


    Since each where method call returns a DetachedCriteria instance, you can use where queries to execute batch operations such as batch updates and deletes. For example, the following query will update all people with the surname "Simpson" to have the surname "Bloggs":

    def query = Person.where {
        lastName == 'Simpson'
    int total = query.updateAll(lastName:"Bloggs")

    Note that one limitation with regards to batch operations is that join queries (queries that query associations) are not allowed.

    To batch delete records you can use the deleteAll method:

    def query = Person.where {
        lastName == 'Simpson'
    int total = query.deleteAll()

    6.4.3 クライテリア

    Criteria is an advanced way to query that uses a Groovy builder to construct potentially complex queries. It is a much better approach than building up query strings using a StringBuffer.
    クライテリアは、潜在的に複雑なクエリを構築するためにGroovyのビルダを利用するという、クエリのためのより進んだ方法です。 これはStringBufferを使ってクエリ文字列を構築するより優れたやり方です。

    Criteria can be used either with the createCriteria or withCriteria methods. The builder uses Hibernate's Criteria API. The nodes on this builder map the static methods found in the Restrictions class of the Hibernate Criteria API. For example:
    クライテリアはcreateCriteriaメソッド、またはwithCriteriaメソッドのいずれかで使用できます。 このビルダーはHibernateのクライテリアAPIを使用します。 ビルダー上のノードはHibernateのクライテリアAPIのRestrictionsクラス内の静的メソッドにマッピングされます。 以下はその例です:

    def c = Account.createCriteria()
    def results = c {
        between("balance", 500, 1000)
        eq("branch", "London")
        or {
            like("holderFirstName", "Fred%")
            like("holderFirstName", "Barney%")
        order("holderLastName", "desc")

    This criteria will select up to 10 Account objects in a List matching the following criteria:

    • balance is between 500 and 1000
    • branch is 'London'
    • holderFirstName starts with 'Fred' or 'Barney'

    • balance500から1000の間である
    • branchLondonである
    • holderFirstNameFredBarneyで始まっている

    The results will be sorted in descending order by holderLastName.

    If no records are found with the above criteria, an empty List is returned.

    Conjunctions and Disjunctions


    As demonstrated in the previous example you can group criteria in a logical OR using an or { } block:
    前の例で提示したように、or { }ブロックを使用し、クライテリアを論理和でグループ化できます。

    or {
        between("balance", 500, 1000)
        eq("branch", "London")

    This also works with logical AND:

    and {
        between("balance", 500, 1000)
        eq("branch", "London")

    And you can also negate using logical NOT:

    not {
        between("balance", 500, 1000)
        eq("branch", "London")

    All top level conditions are implied to be AND'd together.

    Querying Associations


    Associations can be queried by having a node that matches the property name. For example say the Account class had many Transaction objects:
    関連はプロパティ名と一致するノードを持つことで問い合わせができます。 例えば、Accountクラスが1対多の関連としてTransactionオブジェクトを持っているとします:

    class Account {
        static hasMany = [transactions: Transaction]

    We can query this association by using the property name transactions as a builder node:

    def c = Account.createCriteria()
    def now = new Date()
    def results = c.list {
        transactions {
            between('date', now - 10, now)

    The above code will find all the Account instances that have performed transactions within the last 10 days. You can also nest such association queries within logical blocks:
    上記のコードは最近10日以内のtransactionsを持つ全てのAccountインスタンスを検索できます。 また、論理ブロック内に関連のクエリをネストすることもできます:

    def c = Account.createCriteria()
    def now = new Date()
    def results = c.list {
        or {
            between('created', now - 10, now)
            transactions {
                between('date', now - 10, now)

    Here we find all accounts that have either performed transactions in the last 10 days OR have been recently created in the last 10 days.

    Querying with Projections


    Projections may be used to customise the results. Define a "projections" node within the criteria builder tree to use projections. There are equivalent methods within the projections node to the methods found in the Hibernate Projections class:
    プロジェクションは取得した結果をカスタマイズするために使われます。 プロジェクションを使うには、クライテリアビルダーのツリーの中でprojectionsノードを定義します。 プロジェクションノードのメソッドは、HibernateのProjectionsクラスのメソッドに相当します。

    def c = Account.createCriteria()

    def numberOfBranches = c.get { projections { countDistinct('branch') } }

    When multiple fields are specified in the projection, a List of values will be returned. A single value will be returned otherwise.
    プロジェクション内に複数のフィールドが指定された場合、値のリストが返却されます。 そうでなければ、単一の値が返却されます。

    SQL Projections


    The criteria DSL provides access to Hibernate's SQL projection API.

    // Box is a domain class…
    class Box {
        int width
        int height

    // Use SQL projections to retrieve the perimeter and area of all of the Box instances…
    def c = Box.createCriteria()

    def results = c.list { projections { sqlProjection '(2 * (width + height)) as perimeter, (width * height) as area', ['perimeter', 'area'], [INTEGER, INTEGER] } }

    The first argument to the sqlProjection method is the SQL which defines the projections. The second argument is a list of Strings which represent column aliases corresponding to the projected values expressed in the SQL. The third argument is a list of org.hibernate.type.Type instances which correspond to the projected values expressed in the SQL. The API supports all org.hibernate.type.Type objects but constants like INTEGER, LONG, FLOAT etc. are provided by the DSL which correspond to all of the types defined in org.hibernate.type.StandardBasicTypes.
    sqlProjectionメソッドの最初の引数は、プロジェクションを定義するSQLです。 第2引数は、SQLで表現されたプロジェクションの値に対応するカラムのエイリアスの文字列リストです。 第3引数は、SQLで表現されたプロジェクションの値に対応するorg.hibernate.type.Typeインスタンスのリストです。 このAPIはすべてのorg.hibernate.type.Typeオブジェクトをサポートしています。 しかし、INTEGER・LONG・FLOATなどの定数については、org.hibernate.type.StandardBasicTypesで定義されたすべての型に対応付けられているDSLによって提供されています。

    Consider that the following table represents the data in the BOX table.


    The query above would return results like this:

    [[18, 14], [20, 16], [22, 18], [26, 36]]

    Each of the inner lists contains the 2 projected values for each Box, perimeter and area.

    Note that if there are other references in scope wherever your criteria query is expressed that have names that conflict with any of the type constants described above, the code in your criteria will refer to those references, not the type constants provided by the DSL. In the unlikely event of that happening you can disambiguate the conflict by referring to the fully qualified Hibernate type. For example StandardBasicTypes.INTEGER instead of INTEGER.
    もしクライテリアクエリ内から参照できるスコープ内に前述の型定数と重複する名前の変数が宣言されている場合は、クライテリア中のコードは、DSLが提供する型定数ではなく、その変数を利用してしまうことに注意してください。 そのような場合は、完全修飾されたHibernateの型を指定することであいまいさを無くし衝突を回避できます。 例えば、INTEGERの代わりにStandardBasicTypes.INTEGERを指定します。

    If only 1 value is being projected, the alias and the type do not need to be included in a list.

    def results = c.list {
        projections {
          sqlProjection 'sum(width * height) as totalArea', 'totalArea', INTEGER

    That query would return a single result with the value of 84 as the total area of all of the Box instances.

    The DSL supports grouped projections with the sqlGroupProjection method.

    def results = c.list {
        projections {
            sqlGroupProjection 'width, sum(height) as combinedHeightsForThisWidth', 'width', ['width', 'combinedHeightsForThisWidth'], [INTEGER, INTEGER]

    The first argument to the sqlGroupProjection method is the SQL which defines the projections. The second argument represents the group by clause that should be part of the query. That string may be single column name or a comma separated list of column names. The third argument is a list of Strings which represent column aliases corresponding to the projected values expressed in the SQL. The fourth argument is a list of org.hibernate.type.Type instances which correspond to the projected values expressed in the SQL.
    sqlGroupProjectionへの最初の引数は、プロジェクションを定義するSQLです。 第2引数は、クエリの一部となるGROUP BY句を表しています。単一のカラム名または複数のカラム名のカンマ区切り文字列を指定します。 第3引数は、SQLで表現されたプロジェクションの値に対応するカラムのエイリアスの文字列リストです。 第4引数は、SQLで表現されたプロジェクションの値に対応するorg.hibernate.type.Typeインスタンスのリストです。

    The query above is projecting the combined heights of boxes grouped by width and would return results that look like this:
    上記のクエリはwidthによってグループ化した上でheightsを合計した値をプロジェクションしています。 これは以下のような結果を返します:

    [[2, 24], [4, 9]]

    Each of the inner lists contains 2 values. The first value is a box width and the second value is the sum of the heights of all of the boxes which have that width.
    それぞれの内側のリストには2つの値が格納されています。 最初の値はwidthの値、次の値はwidthによってグループ化した上でheightを合計した値となります。

    Using SQL Restrictions

    SQL Restrictionsの使用

    You can access Hibernate's SQL Restrictions capabilities.
    HibernateのSQL Restrictions機能を使用できます。

    def c = Person.createCriteria()

    def peopleWithShortFirstNames = c.list { sqlRestriction "char_length(first_name) <= 4" }

    SQL Restrictions may be parameterized to deal with SQL injection vulnerabilities related to dynamic restrictions.
    SQL Restrictionsは、動的な条件に関連するSQLインジェクションの脆弱性に対処するために、条件に埋め込む値をパラメータ化できます。

    def c = Person.createCriteria()

    def peopleWithShortFirstNames = c.list { sqlRestriction "char_length(first_name) < ? AND char_length(first_name) > ?", [maxValue, minValue] }

    Note that the parameter there is SQL. The first_name attribute referenced in the example refers to the persistence model, not the object model like in HQL queries. The Person property named firstName is mapped to the first_name column in the database and you must refer to that in the sqlRestriction string.

    Also note that the SQL used here is not necessarily portable across databases.

    パラメータがSQLであることに注意してください。 上記の例で参照しているfirst_name属性はHQLクエリのようにオブジェクトモデルではなく、永続化モデルを示します。 PersonfirstNameプロパティはデータベース内のfirst_name列にマッピングされており、sqlRestriction文字列内ではfirst_nameを指定する必要があります。


    Using Scrollable Results


    You can use Hibernate's ScrollableResults feature by calling the scroll method:

    def results = crit.scroll {
    def f = results.first()
    def l = results.last()
    def n = results.next()
    def p = results.previous()

    def future = results.scroll(10) def accountNumber = results.getLong('number')

    To quote the documentation of Hibernate ScrollableResults:

    A result iterator that allows moving around within the results by arbitrary increments. The Query / ScrollableResults pattern is very similar to the JDBC PreparedStatement/ ResultSet pattern and the semantics of methods of this interface are similar to the similarly named methods on ResultSet.
    任意の増分を指定して結果内を自由に移動できる結果イテレータです。 このQuery/ScrollableResultsのパターンは、JDBCのPreparedStatement/ResultSetパターンに非常に似ています。 そして、インタフェースのメソッドの意味も、ResultSet上の似た名前のメソッドと同じような意味になります。

    Contrary to JDBC, columns of results are numbered from zero.

    Setting properties in the Criteria instance


    If a node within the builder tree doesn't match a particular criterion it will attempt to set a property on the Criteria object itself. This allows full access to all the properties in this class. This example calls setMaxResults and setFirstResult on the Criteria instance:
    もしこのビルダツリー内のノードが特定のクライテリアにマッチしない場合は、クライテリアオブジェクト自身のプロパティを設定しようとします。 これは、このクラス内のすべてのプロパティへのフルアクセスを許可します。 この例では、Criteriaインスタンス上のsetMaxResultssetFirstResultを呼んでいます。

    import org.hibernate.FetchMode as FM
    def results = c.list {
        fetchMode("aRelationship", FM.JOIN)

    Querying with Eager Fetching


    In the section on Eager and Lazy Fetching we discussed how to declaratively specify fetching to avoid the N+1 SELECT problem. However, this can also be achieved using a criteria query:
    EagerフェッチとLazyフェッチのセクションでは、N+1 SELECT問題を避けるためにフェッチ方法を宣言的に指定する方法について説明しました。 しかし、このクライテリアを使っても同じことを実現できます。

    def criteria = Task.createCriteria()
    def tasks = criteria.list{
        eq "assignee.id", task.assignee.id
        join 'assignee'
        join 'project'
        order 'priority', 'asc'

    Notice the usage of the join method: it tells the criteria API to use a JOIN to fetch the named associations with the Task instances. It's probably best not to use this for one-to-many associations though, because you will most likely end up with duplicate results. Instead, use the 'select' fetch mode:
    joinメソッドの使い方に注意してください。 これは、Taskインスタンスと指定された関連をフェッチするために、JOINを利用するようにクライテリアAPIに指示します。 とはいえ、最終的に重複した結果が得られることになる可能性が非常に高いため、joinは1対多関連に対して使わないのがおそらくベストです。 代わりにselectフェッチモードを使用しましょう:

    import org.hibernate.FetchMode as FM
    def results = Airport.withCriteria {
        eq "region", "EMEA"
        fetchMode "flights", FM.SELECT
    Although this approach triggers a second query to get the flights association, you will get reliable results - even with the maxResults option.

    fetchMode and join are general settings of the query and can only be specified at the top-level, i.e. you cannot use them inside projections or association constraints.
    FetchModejoinはそのクエリ全体に対する設定のため、トップレベルでのみ指定できます。 つまり、プロジェクションや関連のブロック内では使用できません。

    An important point to bear in mind is that if you include associations in the query constraints, those associations will automatically be eagerly loaded. For example, in this query:
    覚えておくべき重要なこととして、クエリ条件に関連を含んでいる場合は、その関連は自動的にEagerフェッチされるということです。 例えば、次のクエリでは:

    def results = Airport.withCriteria {
        eq "region", "EMEA"
        flights {
            like "number", "BA%"

    the flights collection would be loaded eagerly via a join even though the fetch mode has not been explicitly set.

    Method Reference


    If you invoke the builder with no method name such as:

    c { … }

    The build defaults to listing all the results and hence the above is equivalent to:
    ビルダーのデフォルト動作は全件の一覧取得です。 そのため上記は以下のように書いた場合と同等です:

    c.list { … }

    listThis is the default method. It returns all matching rows.
    getReturns a unique result set, i.e. just one row. The criteria has to be formed that way, that it only queries one row. This method is not to be confused with a limit to just the first row.
    scrollReturns a scrollable result set.
    listDistinctIf subqueries or associations are used, one may end up with the same row multiple times in the result set, this allows listing only distinct entities and is equivalent to DISTINCT_ROOT_ENTITY of the CriteriaSpecification class.
    countReturns the number of matching rows.

    Combining Criteria


    You can combine multiple criteria closures in the following way:

    def emeaCriteria = {
        eq "region", "EMEA"

    def results = Airport.withCriteria { emeaCriteria.delegate = delegate emeaCriteria() flights { like "number", "BA%" } }

    This technique requires that each criteria must refer to the same domain class (i.e. Airport). A more flexible approach is to use Detached Criteria, as described in the following section.
    このテクニックでは、それぞれのクライテリアが同じドメインクラス(ここではAirport)に対するものでなければなりません。 より柔軟なアプローチとして、この後のセクションで説明するDetachedクライテリアの使用があります。

    6.4.4 Detachedクライテリア

    Detached Criteria are criteria queries that are not associated with any given database session/connection. Supported since Grails 2.0, Detached Criteria queries have many uses including allowing you to create common reusable criteria queries, execute subqueries and execute batch updates/deletes.
    Detachedクライテリアは特定のデータベースのセッションやコネクションと結びつかないクライテリアクエリです。 このDetachedクライテリアクエリはGrails 2.0からサポートされており、再利用可能な共通のクライテリアクエリの作成や、サブクエリの実行、一括更新や一括削除といったさまざまな用途があります。

    Building Detached Criteria Queries


    The primary point of entry for using the Detached Criteria is the grails.gorm.DetachedCriteria class which accepts a domain class as the only argument to its constructor:
    Detachedクライテリアを使用するための最初の入り口は、grails.gorm.DetachedCriteriaクラスです。 このクラスはコンストラクタの引数としてドメインクラスを受け取ります:

    import grails.gorm.*
    def criteria = new DetachedCriteria(Person)

    Once you have obtained a reference to a detached criteria instance you can execute where queries or criteria queries to build up the appropriate query. To build a normal criteria query you can use the build method:
    このようにDetachedクライテリアインスタンスへの参照を得ると、必要なクエリを構築するためにwhereクエリ、またはクライテリアクエリを実行できます。 通常のクライテリアクエリを構築するにはbuildメソッドを使います:

    def criteria = new DetachedCriteria(Person).build {
        eq 'lastName', 'Simpson'

    Note that methods on the DetachedCriteria instance do not mutate the original object but instead return a new query. In other words, you have to use the return value of the build method to obtain the mutated criteria object:
    DetachedCriteriaインスタンス上のメソッドは、このオブジェクト自身を変更 しない ことに注意してください。代わりに新たなクエリを返します。 言い換えると変更されたクライテリアオブジェクトを取得するにはbuildメソッドの戻り値を使用する必要があります:

    def criteria = new DetachedCriteria(Person).build {
        eq 'lastName', 'Simpson'
    def bartQuery = criteria.build {
        eq 'firstName', 'Bart'

    Executing Detached Criteria Queries


    Unlike regular criteria, Detached Criteria are lazy, in that no query is executed at the point of definition. Once a Detached Criteria query has been constructed then there are a number of useful query methods which are summarized in the table below:
    通常のクライテリアと異なり、Detachedクライテリアは定義しただけではクエリが実行されません。 Detachedクライテリアを構築したあとは、以下の表にあるような便利なクエリメソッドを使います:

    listList all matching entities
    getReturn a single matching result
    countCount all matching records
    existsReturn true if any matching records exist
    deleteAllDelete all matching records
    updateAll(Map)Update all matching records with the given properties

    As an example the following code will list the first 4 matching records sorted by the firstName property:

    def criteria = new DetachedCriteria(Person).build {
        eq 'lastName', 'Simpson'
    def results = criteria.list(max:4, sort:"firstName")

    You can also supply additional criteria to the list method:

    def results = criteria.list(max:4, sort:"firstName") {
        gt 'age', 30

    To retrieve a single result you can use the get or find methods (which are synonyms):

    Person p = criteria.find() // or criteria.get()

    The DetachedCriteria class itself also implements the Iterable interface which means that it can be treated like a list:

    def criteria = new DetachedCriteria(Person).build {
        eq 'lastName', 'Simpson'
    criteria.each {
        println it.firstName

    In this case the query is only executed when the each method is called. The same applies to all other Groovy collection iteration methods.
    この場合、クエリはeachメソッドが呼ばれたときにだけ1度実行されます。 これは、Groovyがコレクションで提供している他のイテレーションメソッドでも同じです。

    You can also execute dynamic finders on DetachedCriteria just like on domain classes. For example:

    def criteria = new DetachedCriteria(Person).build {
        eq 'lastName', 'Simpson'
    def bart = criteria.findByFirstName("Bart")

    Using Detached Criteria for Subqueries


    Within the context of a regular criteria query you can use DetachedCriteria to execute subquery. For example if you want to find all people who are older than the average age the following query will accomplish that:
    通常のクライテリアのなかで、サブクエリを実行するためにDetachedCriteriaが使えます。 例えば、平均年齢以上のすべての人を検索したい場合は、以下のようにします:

    def results = Person.withCriteria {
         gt "age", new DetachedCriteria(Person).build {
             projections {
                 avg "age"
         order "firstName"

    Notice that in this case the subquery class is the same as the original criteria query class (ie. Person) and hence the query can be shortened to:
    この場合、サブクエリのクラスは、オリジナルのクライテリアのクラス(ここでは@Person)と同じという点に注目してください。 そのため、このクエリは以下のように短く記述できます:

    def results = Person.withCriteria {
         gt "age", {
             projections {
                 avg "age"
         order "firstName"

    If the subquery class differs from the original criteria query then you will have to use the original syntax.

    In the previous example the projection ensured that only a single result was returned (the average age). If your subquery returns multiple results then there are different criteria methods that need to be used to compare the result. For example to find all the people older than the ages 18 to 65 a gtAll query can be used:
    上記の例では、プロジェクションは単一結果のみ(平均年令)が返ることを保証しています。 もしサブクエリが複数の結果を返す場合は、複数の結果を比較するためのクライテリアのメソッドがあります。 例えば年齢が18歳から65歳よりも上のすべての人を検索するには、getAllクエリを使います:

    def results = Person.withCriteria {
        gtAll "age", {
            projections {
                property "age"
            between 'age', 18, 65

    order "firstName" }

    The following table summarizes criteria methods for operating on subqueries that return multiple results:

    gtAllgreater than all subquery results
    geAllgreater than or equal to all subquery results
    ltAllless than all subquery results
    leAllless than or equal to all subquery results
    eqAllequal to all subquery results
    neAllnot equal to all subquery results

    Batch Operations with Detached Criteria


    The DetachedCriteria class can be used to execute batch operations such as batch updates and deletes. For example, the following query will update all people with the surname "Simpson" to have the surname "Bloggs":
    DetachedCriteriaクラスは一括更新・一括削除といったバッチ処理の実行に使えます。 例えば、以下のクエリは姓がSimpsonのすべての人の姓をBloggsに更新します:

    def criteria = new DetachedCriteria(Person).build {
        eq 'lastName', 'Simpson'
    int total = criteria.updateAll(lastName:"Bloggs")

    Note that one limitation with regards to batch operations is that join queries (queries that query associations) are not allowed within the DetachedCriteria instance.

    To batch delete records you can use the deleteAll method:

    def criteria = new DetachedCriteria(Person).build {
        eq 'lastName', 'Simpson'
    int total = criteria.deleteAll()

    6.4.5 Hibernateクエリー言語 (HQL)

    GORM classes also support Hibernate's query language HQL, a very complete reference for which can be found in the Hibernate documentation of the Hibernate documentation.
    GORMのドメインクラスはHibernateのクエリ言語であるHQLもサポートしています。 HQLに関するとても充実したリファレンスがHibernateのドキュメントにあります。

    GORM provides a number of methods that work with HQL including find, findAll and executeQuery. An example of a query can be seen below:
    GORMは、findfindAll、そしてexecuteQueryといった、HQLと連携するいくつかのメソッドを提供しています。 以下はクエリの使用例です:

    def results =
          Book.findAll("from Book as b where b.title like 'Lord of the%'")

    h4. Positional and Named Parameters


    In this case the value passed to the query is hard coded, however you can equally use positional parameters:

    def results =
          Book.findAll("from Book as b where b.title like ?", ["The Shi%"])

    def author = Author.findByName("Stephen King")
    def books = Book.findAll("from Book as book where book.author = ?",

    Or even named parameters:

    def results =
          Book.findAll("from Book as b " +
                       "where b.title like :search or b.author like :search",
                       [search: "The Shi%"])

    def author = Author.findByName("Stephen King")
    def books = Book.findAll("from Book as book where book.author = :author",
                             [author: author])

    h4. Multiline Queries


    Use the line continuation character to separate the query across multiple lines:

    def results = Book.findAll("\
    from Book as b, \
         Author as a \
    where b.author = a and a.surname = ?", ['Smith'])

    Triple-quoted Groovy multiline Strings will NOT work with HQL queries.

    h4. Pagination and Sorting


    You can also perform pagination and sorting whilst using HQL queries. To do so simply specify the pagination options as a Map at the end of the method call and include an "ORDER BY" clause in the HQL:
    HQLクエリを使いながら、ページングとソートを行うこともできます。 これには、メソッドの最後の引数にMapとしてページングオプションを指定し、HQLの中にORDER BY節を追加します:

    def results =
          Book.findAll("from Book as b where " +
                       "b.title like 'Lord of the%' " +
                       "order by b.title asc",
                       [max: 10, offset: 20])

    6.5 高度なGORMの機能

    The following sections cover more advanced usages of GORM including caching, custom mapping and events.

    6.5.1 イベントと自動タイムスタンプ

    GORM supports the registration of events as methods that get fired when certain events occurs such as deletes, inserts and updates. The following is a list of supported events:
    GORMは、削除や新規追加・更新などの特定のイベントが発生したときに処理を行う方法として、イベントの登録をサポートしています。 サポートしているイベントの一覧を以下に示します:

    • beforeInsert - Executed before an object is initially persisted to the database
    • beforeUpdate - Executed before an object is updated
    • beforeDelete - Executed before an object is deleted
    • beforeValidate - Executed before an object is validated
    • afterInsert - Executed after an object is persisted to the database
    • afterUpdate - Executed after an object has been updated
    • afterDelete - Executed after an object has been deleted
    • onLoad - Executed when an object is loaded from the database

    • beforeInsert - データベースにオブジェクトが新規保存される前に実行される
    • beforeUpdate - オブジェクトが更新される前に実行される
    • beforeDelete - オブジェクトが削除される前に実行される
    • beforeValidate - オブジェクトがバリデートされる前に実行される
    • afterInsert - データベースにオブジェクトが新規保存された後に実行される
    • afterUpdate - オブジェクトが更新された後に実行される
    • afterDelete - オブジェクトが削除された後に実行される
    • onLoad - オブジェクトがデータベースからロードされたときに実行される

    To add an event simply register the relevant method with your domain class.

    Do not attempt to flush the session within an event (such as with obj.save(flush:true)). Since events are fired during flushing this will cause a StackOverflowError.
    イベント内で(obj.save(flush:true)のように)セッションをフラッシュしようとしてはいけません。 イベントはフラッシュ処理中の一環として実行されるため、これはStackOverflowErrorを引き起こしてしまいます。

    h3. Event types


    h4. The beforeInsert event


    Fired before an object is saved to the database

    class Person {
       private static final Date NULL_DATE = new Date(0)

    String firstName String lastName Date signupDate = NULL_DATE

    def beforeInsert() { if (signupDate == NULL_DATE) { signupDate = new Date() } } }

    h4. The beforeUpdate event


    Fired before an existing object is updated

    class Person {

    def securityService

    String firstName String lastName String lastUpdatedBy

    static constraints = { lastUpdatedBy nullable: true }

    def beforeUpdate() { lastUpdatedBy = securityService.currentAuthenticatedUsername() } }

    h4. The beforeDelete event


    Fired before an object is deleted.

    class Person {
       String name

    def beforeDelete() { ActivityTrace.withNewSession { new ActivityTrace(eventName: "Person Deleted", data: name).save() } } }

    Notice the usage of withNewSession method above. Since events are triggered whilst Hibernate is flushing using persistence methods like save() and delete() won't result in objects being saved unless you run your operations with a new Session.
    上でwithNewSessionメソッドを利用している点に注目してください。 イベントはHibernateがフラッシュしている最中に実行されるため、新しいSessionで操作を実行しない限り、save()delete()のような永続化メソッドによってオブジェクトを保存することはできません。

    Fortunately the withNewSession method lets you share the same transactional JDBC connection even though you're using a different underlying Session.

    h4. The beforeValidate event


    Fired before an object is validated.

    class Person {
       String name

    static constraints = { name size: 5..45 }

    def beforeValidate() { name = name?.trim() } }

    The beforeValidate method is run before any validators are run.

    Validation may run more often than you think. It is triggered by the validate() and save() methods as you'd expect, but it is also typically triggered just before the view is rendered as well. So when writing beforeValidate() implementations, make sure that they can handle being called multiple times with the same property values.
    バリデーションはあなたが考えるよりも多くの頻度で実行される可能性があります。 あなたの予想通りvalidate()save()メソッドによって実行されますが、ビューがレンダリングされる直前にもよく実行されます。 このため、beforeValidateの実装を書くときには、同じプロパティ値で複数回呼ばれても処理できるように気をつけてください。

    GORM supports an overloaded version of beforeValidate which accepts a List parameter which may include the names of the properties which are about to be validated. This version of beforeValidate will be called when the validate method has been invoked and passed a List of property names as an argument.
    GORMは、バリデートしようとするプロパティ名を含んだListパラメータを受け取る、オーバロードされたバージョンのbeforeValidateをサポートします。 このbeforeValidateは、validateメソッドが実行されてプロパティ名のListを引数として渡されたときに呼ばれます。

    class Person {
       String name
       String town
       Integer age

    static constraints = { name size: 5..45 age range: 4..99 }

    def beforeValidate(List propertiesBeingValidated) { // do pre validation work based on propertiesBeingValidated } }

    def p = new Person(name: 'Jacob Brown', age: 10) p.validate(['age', 'name'])

    Note that when validate is triggered indirectly because of a call to the save method that the validate method is being invoked with no arguments, not a List that includes all of the property names.

    Either or both versions of beforeValidate may be defined in a domain class. GORM will prefer the List version if a List is passed to validate but will fall back on the no-arg version if the List version does not exist. Likewise, GORM will prefer the no-arg version if no arguments are passed to validate but will fall back on the List version if the no-arg version does not exist. In that case, null is passed to beforeValidate.
    beforeValidateのいずれかまたは両方のバージョンをドメインクラスに定義できます。 GORMは、Listvalidateに渡されればListバージョンを選ぼうとしますが、もしListバージョンが存在しなければ、引数なしバージョンにフォールバックします。 同様に、GORMはvalidateに引数が渡されなければ引数なしバージョンを選ぼうとしますが、もし引数なしバージョンが存在しなければ、Listバージョンにフォールバックします。 そのような場合、nullbeforeValidateに渡されます。

    h4. The onLoad/beforeLoad event


    Fired immediately before an object is loaded from the database:

    class Person {
       String name
       Date dateCreated
       Date lastUpdated

    def onLoad() { log.debug "Loading ${id}" } }

    beforeLoad() is effectively a synonym for onLoad(), so only declare one or the other.

    h4. The afterLoad event


    Fired immediately after an object is loaded from the database:

    class Person {
       String name
       Date dateCreated
       Date lastUpdated

    def afterLoad() { name = "I'm loaded" } }

    h4. Custom Event Listeners


    As of Grails 2.0 there is a new API for plugins and applications to register and listen for persistence events. This API is not tied to Hibernate and also works for other persistence plugins such as the MongoDB plugin for GORM.
    Grails 2.0以降では、永続化イベントを登録・監視するためのプラグインとアプリケーション向けの新しいAPIがあります。 このAPIはHibernateに依存していないため、MongoDB plugin for GORMのような他の永続化プラグインでも動作します。

    To use this API you need to subclass AbstractPersistenceEventListener (in package org.grails.datastore.mapping.engine.event ) and implement the methods onPersistenceEvent and supportsEventType. You also must provide a reference to the datastore to the listener. The simplest possible implementation can be seen below:
    このAPIを使うには、( org.grails.datastore.mapping.engine.event パッケージの)AbstractPersistenceEventListenerのサブクラスと、そのonPersistenceEventsupportsEventTypeメソッドの実装が必要です。 また、リスナにデータストアへの参照を渡さなければなりません。 もっとも単純な実装を以下に示します:

    public MyPersistenceListener(final Datastore datastore) {

    @Override protected void onPersistenceEvent(final AbstractPersistenceEvent event) { switch(event.eventType) { case PreInsert: println "PRE INSERT ${event.entityObject}" break case PostInsert: println "POST INSERT ${event.entityObject}" break case PreUpdate: println "PRE UPDATE ${event.entityObject}" break; case PostUpdate: println "POST UPDATE ${event.entityObject}" break; case PreDelete: println "PRE DELETE ${event.entityObject}" break; case PostDelete: println "POST DELETE ${event.entityObject}" break; case PreLoad: println "PRE LOAD ${event.entityObject}" break; case PostLoad: println "POST LOAD ${event.entityObject}" break; } }

    @Override public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { return true }

    The AbstractPersistenceEvent class has many subclasses (PreInsertEvent, PostInsertEvent etc.) that provide further information specific to the event. A cancel() method is also provided on the event which allows you to veto an insert, update or delete operation.
    AbstractPersistenceEventクラスは、それぞれのイベントに特有の情報を提供する多くのサブクラス(PreInsertEvent, PostInsertEvent, 等)を持っています。 また、イベント内で新規追加・更新・削除操作をキャンセルできるcancel()メソッドも提供されます。

    Once you have created your event listener you need to register it with the ApplicationContext. This can be done in BootStrap.groovy:
    独自イベントリスナを作成したら、ApplicationContextに登録する必要があります。 これはBootStrap.groovyで行えます:

    def init = {
        application.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
            applicationContext.addApplicationListener new MyPersistenceListener(datastore)

    or use this in a plugin:

    def doWithApplicationContext = { applicationContext ->
        application.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
            applicationContext.addApplicationListener new MyPersistenceListener(datastore)

    h4. Hibernate Events


    It is generally encouraged to use the non-Hibernate specific API described above, but if you need access to more detailed Hibernate events then you can define custom Hibernate-specific event listeners.
    一般的には前述したHibernate固有ではないAPIの使用が推奨されます。 しかし、より詳細なHibernateイベントにアクセスする必要がある場合は、Hibernate固有のカスタムイベントリスナを定義できます。

    You can also register event handler classes in an application's grails-app/conf/spring/resources.groovy or in the doWithSpring closure in a plugin descriptor by registering a Spring bean named hibernateEventListeners. This bean has one property, listenerMap which specifies the listeners to register for various Hibernate events.
    また、アプリケーションのgrails-app/conf/spring/resources.groovyやプラグインディスクリプタのdoWithSpringクロージャで、hibernateEventListenersという名前でSpringビーンを登録することで、イベントハンドラクラスを登録することができます。 このビーンはlistenerMapという1つのプロパティを持ちます。このプロパティでは様々なHibernateイベントに対して登録するリスナを指定します。

    The values of the Map are instances of classes that implement one or more Hibernate listener interfaces. You can use one class that implements all of the required interfaces, or one concrete class per interface, or any combination. The valid Map keys and corresponding interfaces are listed here:
    Mapの値は、Hibernateのリスナインターフェイスを1つ以上実装したクラスのインスタンスです。 すべての必要なインターフェイスを実装した1つのクラスを使ったり、1つのインターフェイスごとに1つの実装クラスを使うことができます。またその組合せも可能です。 マップの有効なキーと対応するインターフェイスを以下に列挙します:


    For example, you could register a class AuditEventListener which implements PostInsertEventListener, PostUpdateEventListener, and PostDeleteEventListener using the following in an application:

    beans = {


    hibernateEventListeners(HibernateEventListeners) { listenerMap = ['post-insert': auditListener, 'post-update': auditListener, 'post-delete': auditListener] } }

    or use this in a plugin:

    def doWithSpring = {


    hibernateEventListeners(HibernateEventListeners) { listenerMap = ['post-insert': auditListener, 'post-update': auditListener, 'post-delete': auditListener] } }

    h4. Automatic timestamping


    If you define a dateCreated property it will be set to the current date for you when you create new instances. Likewise, if you define a lastUpdated property it will be automatically be updated for you when you change persistent instances.
    dateCreatedプロパティを定義した場合、新しいインスタンスを新規保存したときに現在の日時がセットされます。 同様に、lastUpdatedプロパティを定義した場合は、永続化されたインスタンスが変更されるときにその値が自動的に更新されます。

    If this is not the behaviour you want you can disable this feature with:

    class Person {
       Date dateCreated
       Date lastUpdated
       static mapping = {
          autoTimestamp false

    If you have nullable: false constraints on either dateCreated or lastUpdated, your domain instances will fail validation - probably not what you want. Omit constraints from these properties unless you disable automatic timestamping.
    もしdateCreatedlastUpdatednullable: falseを指定すると、おそらくあなたの望んだ動作ではないでしょうが、ドメインインスタンスのバリデーションに失敗します。 自動タイムスタンプを無効化しない場合は、これらのプロパティに制約を与えないでください。

    6.5.2 O/Rマッピングのカスタマイズ

    Grails domain classes can be mapped onto many legacy schemas with an Object Relational Mapping DSL (domain specific language). The following sections takes you through what is possible with the ORM DSL.
    GrailsのドメインクラスはObject Relation Mapping DSL(Domain Specific Language; ドメイン特化言語)を利用して、多くのレガシースキーマにマッピングさせることができます。 この後に続くセクションでは、ORM DSLを使って何ができるかをひとつひとつ見ていきます。

    None of this is necessary if you are happy to stick to the conventions defined by GORM for table names, column names and so on. You only needs this functionality if you need to tailor the way GORM maps onto legacy schemas or configures caching
    もしあなたがGORMが定めるテーブル名やカラム名などの規約で満足しているのであれば、これはまったく必要ありません。 GORMをレガシースキーマにマッピングしたり、キャッシュを設定したりするようなカスタマイズが必要な場合にのみ、この機能が必要となります。

    Custom mappings are defined using a static mapping block defined within your domain class:

    class Person {
        static mapping = {
            version false
            autoTimestamp false

    You can also configure global mappings in Config.groovy (or an external config file) using this setting:

    grails.gorm.default.mapping = {
        version false
        autoTimestamp false

    It has the same syntax as the standard mapping block but it applies to all your domain classes! You can then override these defaults within the mapping block of a domain class.
    これは通常のmappingブロックと同じシンタックスを持ちますが、すべてのドメインクラスに適用されます。 更に、ドメインクラスのmapping内でこれらのデフォルト設定を上書きすることもできます。 テーブル名、カラム名

    h4. Table names


    The database table name which the class maps to can be customized using the table method:

    class Person {
        static mapping = {
            table 'people'

    In this case the class would be mapped to a table called people instead of the default name of person.

    h4. Column names


    It is also possible to customize the mapping for individual columns onto the database. For example to change the name you can do:
    また、個々のカラムに対するデータベースとの対応付けもカスタマイズできます。 名前を変更する例として、次のように書けます:

    class Person {

    String firstName

    static mapping = { table 'people' firstName column: 'First_Name' } }

    Here firstName is a dynamic method within the mapping Closure that has a single Map parameter. Since its name corresponds to a domain class persistent field, the parameter values (in this case just "column") are used to configure the mapping for that property.
    ここで、firstNamemappingクロージャ内におけるダイナミックメソッドで、Map型の引数を1つ取ります。 その名前はドメインクラスの永続化フィールドと対応していて、Map引数の値(この例ではちょうど"column"の値)はこのプロパティとのマッピングに使われます。

    h4. Column type


    GORM supports configuration of Hibernate types with the DSL using the type attribute. This includes specifing user types that implement the Hibernate org.hibernate.usertype.UserType interface, which allows complete customization of how a type is persisted. As an example if you had a PostCodeType you could use it as follows:

    GORMでは、type属性を利用したDSLによって、Hibernateの型を指定できます。 Hibernateのorg.hibernate.usertype.UserTypeインターフェイスを実装したユーザ型も指定できます。 これを使えば、ある型がどのように永続化されるかを完全にカスタマイズできます。

    class Address {

    String number String postCode

    static mapping = { postCode type: PostCodeType } }

    Alternatively if you just wanted to map it to one of Hibernate's basic types other than the default chosen by Grails you could use:

    class Address {

    String number String postCode

    static mapping = { postCode type: 'text' } }

    This would make the postCode column map to the default large-text type for the database you're using (for example TEXT or CLOB).

    See the Hibernate documentation regarding Basic Types for further information.

    h4. Many-to-One/One-to-One Mappings


    In the case of associations it is also possible to configure the foreign keys used to map associations. In the case of a many-to-one or one-to-one association this is exactly the same as any regular column. For example consider the following:
    関連の場合、対応付けに使われる外部キーを変更することもできます。 多対1と1対1関連の場合、この方法は普通のカラムの場合とまったく同じです。 例えば、以下を考えます:

    class Person {

    String firstName Address address

    static mapping = { table 'people' firstName column: 'First_Name' address column: 'Person_Address_Id' } }

    By default the address association would map to a foreign key column called address_id. By using the above mapping we have changed the name of the foreign key column to Person_Adress_Id.
    デフォルトでは、address関連はaddress_idという名前の外部キーカラムに対応付けられます。 上記のマッピングを使うと、その外部キーカラムの名前がPerson_Adress_Idに変更されます。

    h4. One-to-Many Mapping


    With a bidirectional one-to-many you can change the foreign key column used by changing the column name on the many side of the association as per the example in the previous section on one-to-one associations. However, with unidirectional associations the foreign key needs to be specified on the association itself. For example given a unidirectional one-to-many relationship between Person and Address the following code will change the foreign key in the address table:
    双方向の1対多では、前のセクションの1対1関連の例に従って、関連における「多」側のカラム名を変更することで、外部キーカラムを変更することができます。 一方、単方向の1対多関連の場合は、Grailsはデフォルトで結合テーブルを利用します。 例えば、PersonAddress間の単方向1対多関連では、以下のコードでaddressテーブルに対する外部キーカラム名を変更できます。

    class Person {

    String firstName

    static hasMany = [addresses: Address]

    static mapping = { table 'people' firstName column: 'First_Name' addresses column: 'Person_Address_Id' } }

    If you don't want the column to be in the address table, but instead some intermediate join table you can use the joinTable parameter:

    class Person {

    String firstName

    static hasMany = [addresses: Address]

    static mapping = { table 'people' firstName column: 'First_Name' addresses joinTable: [name: 'Person_Addresses', key: 'Person_Id', column: 'Address_Id'] } }

    h4. Many-to-Many Mapping


    Grails, by default maps a many-to-many association using a join table. For example consider this many-to-many association:
    Grailsは、デフォルトで結合テーブルを利用して多対多関連を実現します。 例えば、次の多対多関連を考えます:

    class Group {
        static hasMany = [people: Person]

    class Person {
        static belongsTo = Group
        static hasMany = [groups: Group]

    In this case Grails will create a join table called group_person containing foreign keys called person_id and group_id referencing the person and group tables. To change the column names you can specify a column within the mappings for each class.
    この場合、Grailsはgroup_personという名前の結合テーブルを生成します。 この結合テーブルは、persongroupテーブルを参照するperson_idgroup_idという名前の外部キーを持っています。 このカラム名を変更するには、それぞれのクラスのmapping内にcolumnを指定します。

    class Group {
       static mapping = {
           people column: 'Group_Person_Id'
    class Person {
       static mapping = {
           groups column: 'Group_Group_Id'

    You can also specify the name of the join table to use:

    class Group {
       static mapping = {
           people column: 'Group_Person_Id',
                  joinTable: 'PERSON_GROUP_ASSOCIATIONS'
    class Person {
       static mapping = {
           groups column: 'Group_Group_Id',
                  joinTable: 'PERSON_GROUP_ASSOCIATIONS'
    } キャッシングストラテジ

    h4. Setting up caching


    Hibernate features a second-level cache with a customizable cache provider. This needs to be configured in the grails-app/conf/DataSource.groovy file as follows:
    Hibernate はカスタマイズ可能なキャッシュプロバイダによる二次キャッシュを持っています。 利用するにはgrails-app/conf/DataSource.groovyで次のような設定が必要です:

    hibernate {

    You can customize any of these settings, for example to use a distributed caching mechanism.

    For further reading on caching and in particular Hibernate's second-level cache, refer to the Hibernate documentation on the subject.

    h4. Caching instances


    Call the cache method in your mapping block to enable caching with the default settings:

    class Person {
        static mapping = {
            table 'people'
            cache true

    This will configure a 'read-write' cache that includes both lazy and non-lazy properties. You can customize this further:
    上の設定では、lazyとnon-lazyの両方のプロパティを含んだread-writeキャッシュが設定されます。 次のようにもっと細かく設定することもできます:

    class Person {
        static mapping = {
            table 'people'
            cache usage: 'read-only', include: 'non-lazy'

    h4. Caching associations


    As well as the ability to use Hibernate's second level cache to cache instances you can also cache collections (associations) of objects. For example:
    Hibernateの2次キャッシュは、インスタンスのキャッシュだけではなく、オブジェクトのコレクション(関連)もキャッシュできます。 例えば:

    class Person {

    String firstName

    static hasMany = [addresses: Address]

    static mapping = { table 'people' version false addresses column: 'Address', cache: true } }

    class Address {
        String number
        String postCode

    This will enable a 'read-write' caching mechanism on the addresses collection. You can also use:
    これはaddressesコレクション上でのread-writeキャッシュ機構を有効にします。 より細かくカスタマイズするために

    cache: 'read-write' // or 'read-only' or 'transactional'

    to further configure the cache usage.

    h4. Caching Queries


    You can cache queries such as dynamic finders and criteria. To do so using a dynamic finder you can pass the cache argument:
    ダイナミックファインダやクライテリアのようなクエリをキャッシュすることもできます。 ダイナミックファインダをキャッシュするためには、cache引数を渡します:

    def person = Person.findByFirstName("Fred", [cache: true])

    In order for the results of the query to be cached, you must enable caching in your mapping as discussed in the previous section.

    You can also cache criteria queries:

    def people = Person.withCriteria {
        like('firstName', 'Fr%')
        cache true

    h4. Cache usages


    Below is a description of the different cache settings and their usages:

    • read-only - If your application needs to read but never modify instances of a persistent class, a read-only cache may be used.
    • read-write - If the application needs to update data, a read-write cache might be appropriate.
    • nonstrict-read-write - If the application only occasionally needs to update data (ie. if it is very unlikely that two transactions would try to update the same item simultaneously) and strict transaction isolation is not required, a nonstrict-read-write cache might be appropriate.
    • transactional - The transactional cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache may only be used in a JTA environment and you must specify hibernate.transaction.manager_lookup_class in the grails-app/conf/DataSource.groovy file's hibernate config.

    • read-only -アプリケーションが永続化されたデータを変更せず単に読むだけであれば、read-onlyキャッシュが使えます。
    • read-write - アプリケーションがデータを更新する必要があれば、read-writeキャッシュが適しているかも知れません。
    • nonstrict-read-write - アプリケーションがごくたまにデータを更新するぐらいで(すなわち、2つのトランザクションが同時に同一の項目を更新することがほとんどなく)、かつ、厳密なトランザクション分離を必要としないのであれば、nonstrict-read-writeキャッシュが適しているかも知れません。
    • transactional - このキャッシュ戦略はJBoss TreeCacheのようなトランザクション対応キャッシュプロバイダを完全にサポートします。このようなキャッシュはJTA環境でのみ使えます。grails-app/conf/DataSource.groovyファイルのhibernate設定にhibernate.transaction.manager_lookup_classを指定も必要です。 継承ストラテジ

    By default GORM classes use table-per-hierarchy inheritance mapping. This has the disadvantage that columns cannot have a NOT-NULL constraint applied to them at the database level. If you would prefer to use a table-per-subclass inheritance strategy you can do so as follows:
    デフォルトでは、GORMのクラスはtable-per-hierarchy継承マッピングを用います。 この場合、データベースレベルでNOT-NULL制約が適用できないというデメリットがあります。 もしtable-per-subclass継承を使いたければ、次のように書くことができます:

    class Payment {
        Integer amount

    static mapping = { tablePerHierarchy false } }

    class CreditCardPayment extends Payment { String cardNumber }

    The mapping of the root Payment class specifies that it will not be using table-per-hierarchy mapping for all child classes.
    Paymentスーパクラスのマッピングで、すべてのサブクラスに対してtable-per-hierarchyマッピングを使わないように指定しています。 データベース識別子のカスタマイズ

    You can customize how GORM generates identifiers for the database using the DSL. By default GORM relies on the native database mechanism for generating ids. This is by far the best approach, but there are still many schemas that have different approaches to identity.
    DSLを用いて、GORMがデータベース上の識別子を生成する方法をカスタマイズできます。 デフォルトでは、GORMはIDの生成をデータベース固有の機構に頼っています。 これは最良のアプローチですが、アイデンティティの管理方法として異なるアプローチをとるスキーマも多くあります。

    To deal with this Hibernate defines the concept of an id generator. You can customize the id generator and the column it maps to as follows:
    それらを取り扱えるように、HibernateはIDジェネレータという概念を定義しています。 IDジェネレータとそれに対応するカラムは次のようにカスタマイズできます:

    class Person {
        static mapping = {
            table 'people'
            version false
            id generator: 'hilo',
               params: [table: 'hi_value',
                        column: 'next_value',
                        max_lo: 100]

    In this case we're using one of Hibernate's built in 'hilo' generators that uses a separate table to generate ids.

    For more information on the different Hibernate generators refer to the Hibernate reference documentation

    Although you don't typically specify the id field (Grails adds it for you) you can still configure its mapping like the other properties. For example to customise the column for the id property you can do:
    Grailsが自動的に追加してくれるため、通常はわざわざidフィールドを指定することはありませんが、 他のプロパティと同様にマッピングを変更することもできます:

    class Person {
        static mapping = {
            table 'people'
            version false
            id column: 'person_id'
    } 複合主キー

    GORM supports the concept of composite identifiers (identifiers composed from 2 or more properties). It is not an approach we recommend, but is available to you if you need it:
    GORMは複合主キー(2つ以上のプロパティから構成される識別子)をサポートしています。 複合主キーはお勧めの方法ではありませんが、必要ならば利用可能です。

    import org.apache.commons.lang.builder.HashCodeBuilder

    class Person implements Serializable {

    String firstName String lastName

    boolean equals(other) { if (!(other instanceof Person)) { return false }

    other.firstName == firstName && other.lastName == lastName }

    int hashCode() { def builder = new HashCodeBuilder() builder.append firstName builder.append lastName builder.toHashCode() }

    static mapping = { id composite: ['firstName', 'lastName'] } }

    The above will create a composite id of the firstName and lastName properties of the Person class. To retrieve an instance by id you use a prototype of the object itself:
    上の例では、PersonクラスのfirstNamelastNameプロパティを複合主キーにしています。 IDでインスタンスを取得するためには、そのドメインクラスの未保存のインスタンスを検索条件として使用します:

    def p = Person.get(new Person(firstName: "Fred", lastName: "Flintstone"))
    println p.firstName

    Domain classes mapped with composite primary keys must implement the Serializable interface and override the equals and hashCode methods, using the properties in the composite key for the calculations. The example above uses a HashCodeBuilder for convenience but it's fine to implement it yourself.
    複合主キーを用いるドメインクラスでは、Serializableインターフェイスの実装とequalshashCodeメソッドのオーバライドが必要です。 これによって複合キーのプロパティを同一性の算定に利用できるようになります。 前述の例では、簡便のためHashCodeBuilderを利用しましたが、もちろん自分で実装しても構いません。

    Another important consideration when using composite primary keys is associations. If for example you have a many-to-one association where the foreign keys are stored in the associated table then 2 columns will be present in the associated table.
    複合主キーを利用する上で、もう一つ抑えておかなければならないのが関連です。 例えば多対1関連の場合、外部キーが関連元テーブル上に格納されますが、上記のように複合主キーを利用すると外部キー用に2つのカラムが必要なことになります。

    For example consider the following domain class:

    class Address {
        Person person

    In this case the address table will have an additional two columns called person_first_name and person_last_name. If you wish the change the mapping of these columns then you can do so using the following technique:
    この場合、addressテーブルには、person_first_nameperson_last_nameという2つのカラムが追加されることになります。 もし、これらのカラムへの対応付けを変更したいのであれば、次のようにできます:

    class Address {
        Person person
        static mapping = {
            columns {
    		    person {
                    column name: "FirstName"
                    column name: "LastName"
    } データベースインデックス

    To get the best performance out of your queries it is often necessary to tailor the table index definitions. How you tailor them is domain specific and a matter of monitoring usage patterns of your queries. With GORM's DSL you can specify which columns are used in which indexes:
    クエリに対してベストな性能を得るために、多くの場合は、テーブルに対するインデックス定義の追加が必要となります。 GORMのDSLで、どのカラムがどのインデックスを使うかを指定することができます。

    class Person {
        String firstName
        String address
        static mapping = {
            table 'people'
            version false
            id column: 'person_id'
            firstName column: 'First_Name', index: 'Name_Idx'
            address column: 'Address', index: 'Name_Idx,Address_Index'

    Note that you cannot have any spaces in the value of the index attribute; in this example index:'Name_Idx, Address_Index' will cause an error.
    index属性の値にスペースを入れることはできないことに注意してください。 例えば、index:'Name_Idx, Address_Index'はエラーになります。 楽観的ロックとバージョニング

    As discussed in the section on Optimistic and Pessimistic Locking, by default GORM uses optimistic locking and automatically injects a version property into every class which is in turn mapped to a version column at the database level.

    If you're mapping to a legacy schema that doesn't have version columns (or there's some other reason why you don't want/need this feature) you can disable this with the version method:

    class Person {
        static mapping = {
            table 'people'
            version false

    If you disable optimistic locking you are essentially on your own with regards to concurrent updates and are open to the risk of users losing data (due to data overriding) unless you use pessimistic locking

    h4. Version columns types


    By default Grails maps the version property as a Long that gets incremented by one each time an instance is updated. But Hibernate also supports using a Timestamp, for example:
    Grailsはデフォルトで、versionプロパティをLong型にマッピングし、インスタンスが更新されるごとにインクリメントします。 しかし、HibernateはTimetamp型もサポートしています。例えば:

    import java.sql.Timestamp

    class Person {

    … Timestamp version

    static mapping = { table 'people' } }

    There's a slight risk that two updates occurring at nearly the same time on a fast server can end up with the same timestamp value but this risk is very low. One benefit of using a Timestamp instead of a Long is that you combine the optimistic locking and last-updated semantics into a single column.
    高性能なサーバ上でほぼ同時に発生した2つの更新が同一のタイムスタンプ値になってしまう、というリスクが僅かながらあります。しかし、このリスクは非常に小さいです。 Long型の代わりにTimestamp型を使うメリットの1つは、1つのカラムで楽観的ロックと最終更新日時の意味を兼任できることです。 EagerフェッチとLazyフェッチ

    h4. Lazy Collections


    As discussed in the section on Eager and Lazy fetching, GORM collections are lazily loaded by default but you can change this behaviour with the ORM DSL. There are several options available to you, but the most common ones are:
    永続化の基礎のEagerフェッチとLazyフェッチのセクションで書いたように、GORMのコレクションはデフォルトでLazyにロードされます。 しかし、ORM DSLでこの振る舞いを変更することができます。 いくつかのオプションが使えますが、もっともよく使われるのは次の2つです:
    • lazy: false
    • fetch: 'join'

    and they're used like this:

    class Person {

    String firstName Pet pet

    static hasMany = [addresses: Address]

    static mapping = { addresses lazy: false pet fetch: 'join' } }

    class Address {
        String street
        String postCode

    class Pet {
        String name

    The first option, lazy: false , ensures that when a Person instance is loaded, its addresses collection is loaded at the same time with a second SELECT. The second option is basically the same, except the collection is loaded with a JOIN rather than another SELECT. Typically you want to reduce the number of queries, so fetch: 'join' is the more appropriate option. On the other hand, it could feasibly be the more expensive approach if your domain model and data result in more and larger results than would otherwise be necessary.
    最初のオプションのlazy: falseは、Personインスタンスがロードされるときに、同時に2本目のSELECTが発行されてaddressesコレクションがロードされることを保証します。 2つめのオプションは別のSELECT文ではなくJOIN構文によってロードされる点を除けば、基本的に同じです。 一般的にクエリの数を減らしたいときは、fetch: 'join'は適切なオプションです。 一方で、ドメインモデルとデータが大量にヒットしてしまう場合、JOINはより高コストなアプローチになってしまう可能性もあります。

    For more advanced users, the other settings available are:
    1. batchSize: N
    2. lazy: false, batchSize: N

    where N is an integer. These let you fetch results in batches, with one query per batch. As a simple example, consider this mapping for Person:
    Nは整数とします。 これによって結果をバッチでフェッチできます。 それぞれのバッチごとに1つのクエリが発行されます。 単純な例として、Personでのマッピングを考えます。

    class Person {

    String firstName Pet pet

    static mapping = { pet batchSize: 5 } }

    If a query returns multiple Person instances, then when we access the first pet property, Hibernate will fetch that Pet plus the four next ones. You can get the same behaviour with eager loading by combining batchSize with the lazy: false option. You can find out more about these options in the Hibernate user guide and this primer on fetching strategies. Note that ORM DSL does not currently support the "subselect" fetching strategy.
    クエリが複数のPersonインスタンスを返す場合、最初のPersonインスタンスのpetプロパティにアクセスしたときに、HibernateはそのPersonインスタンスに関連するPetインスタンスと、それに続く4つのPetインスタンスをフェッチします。 batchSizelazy: falseオプションを同時に指定したEagerフェッチの場合も同じ挙動になります。 Hibernateユーザガイドのフェッチ戦略フェッチ戦略入門で、これらのオプションについてもっと情報を得ることができます。 ORM DSLは今のところ「subselect」フェッチ戦略をサポートしていないことに注意してください。

    h4. Lazy Single-Ended Associations


    In GORM, one-to-one and many-to-one associations are by default lazy. Non-lazy single ended associations can be problematic when you load many entities because each non-lazy association will result in an extra SELECT statement. If the associated entities also have non-lazy associations, the number of queries grows significantly!
    GORMでは、1対1と多対1関連はデフォルトでLazyです。 非Lazyの単一終端関連では、大量のエンティティをロードするときに問題が発生する可能性があります。 非Lazy関連ごとに追加のSELECT文を発行してしまうためです。 関連エンティティが更に非Lazy関連を持つ場合、クエリは相当な数になってしまいます!

    Use the same technique as for lazy collections to make a one-to-one or many-to-one association non-lazy/eager:

    class Person {
        String firstName

    class Address {

    String street String postCode

    static belongsTo = [person: Person]

    static mapping = { person lazy: false } }

    Here we configure GORM to load the associated Person instance (through the person property) whenever an Address is loaded.

    h4. Lazy Single-Ended Associations and Proxies


    Hibernate uses runtime-generated proxies to facilitate single-ended lazy associations; Hibernate dynamically subclasses the entity class to create the proxy.
    HibernateはLazy単一終端関連を扱うためにプロキシを実行時に生成して利用しています。 Hibernateはプロキシを生成するためにエンティティクラスを動的にサブクラス化します。

    Consider the previous example but with a lazily-loaded person association: Hibernate will set the person property to a proxy that is a subclass of Person. When you call any of the getters (except for the id property) or setters on that proxy, Hibernate will load the entity from the database.
    前項の例で、person関連がLazyロードされる場合を考えます。 HibernateはPersonのサブクラスであるプロキシをpersonプロパティにセットします。 そのプロキシに対してsetterか(idプロパティ以外の)getterを呼んだとき、Hibernateはデータベースからそのエンティティをロードします。

    Unfortunately this technique can produce surprising results. Consider the following example classes:
    残念なことに、この機構は驚くべき結果をもたらします。 以下のようなサンプルクラスを考えます:

    class Pet {
        String name

    class Dog extends Pet {

    class Person {
        String name
        Pet pet

    and assume that we have a single Person instance with a Dog as the pet. The following code will work as you would expect:
    ここで、petとしてDogを持っている1つのPersonインスタンスがあると仮定します。 以下のコードは期待通りに動作します:

    def person = Person.get(1)
    assert person.pet instanceof Dog
    assert Pet.get(person.petId) instanceof Dog

    But this won't:

    def person = Person.get(1)
    assert person.pet instanceof Dog
    assert Pet.list()[0] instanceof Dog

    The second assertion fails, and to add to the confusion, this will work:
    2番目のアサーションが失敗します。 混乱がさらに深まるでしょうが、次のコードは動作します。

    assert Pet.list()[0] instanceof Dog

    What's going on here? It's down to a combination of how proxies work and the guarantees that the Hibernate session makes. When you load the Person instance, Hibernate creates a proxy for its pet relation and attaches it to the session. Once that happens, whenever you retrieve that Pet instance with a query, a get(), or the pet relation within the same session , Hibernate gives you the proxy.
    一体何が起こっているのでしょうか? この原因はプロキシの働きとHibernateセッションによる1次キャッシュの連携です。 Personインスタンスをロードしたとき、Hibernateはpetプロパティ用にプロキシを生成してセッションにアタッチします。 一度その状態になってしまうと、 同一セッション内で クエリやget()petプロパティを経由してPetインスタンスを取得するたびに、Hibernateはセッションに登録されているプロキシを返します。

    Fortunately for us, GORM automatically unwraps the proxy when you use get() and findBy*(), or when you directly access the relation. That means you don't have to worry at all about proxies in the majority of cases. But GORM doesn't do that for objects returned with a query that returns a list, such as list() and findAllBy*(). However, if Hibernate hasn't attached the proxy to the session, those queries will return the real instances - hence why the last example works.
    幸いなことに、GORMはget()findBy*()を使ったとき、または、直接関連プロパティにアクセスしたときには、自動的にプロキシをアンラップしてくれます。 これは大部分のケースにおいては、プロキシについて少しも心配する必要がないことを意味します。 しかし、list()findAllBy*()のようなリストを返すクエリによって取得したオブジェクトに対しては、GORMはそのようなサポートをしてくれません。 しかし、Hibernateがプロキシをセッションにアタッチしていなければ、これらのクエリはプロキシではない本物のインスタンスを返します。このため、先ほどの最後の例はうまく動作したのです。

    You can protect yourself to a degree from this problem by using the instanceOf method by GORM:

    def person = Person.get(1)
    assert Pet.list()[0].instanceOf(Dog)

    However, it won't help here if casting is involved. For example, the following code will throw a ClassCastException because the first pet in the list is a proxy instance with a class that is neither Dog nor a sub-class of Dog:
    しかし、キャストを伴う場合はこれでは解決できません。 たとえば、以下のコードはClassCastExceptionをスローします。 なぜなら、リスト中の最初のペットがDogでもDogのサブクラスでもないプロキシインスタンスだからです。

    def person = Person.get(1)
    Dog pet = Pet.list()[0]

    Of course, it's best not to use static types in this situation. If you use an untyped variable for the pet instead, you can access any Dog properties or methods on the instance without any problems.
    もちろん、この場合は静的型を使わないのがベストです。 代わりに型宣言の無い変数をpetに使えば、問題なくそのインスタンス上のDogプロパティやメソッドにアクセスできます。

    These days it's rare that you will come across this issue, but it's best to be aware of it just in case. At least you will know why such an error occurs and be able to work around it.
    最近はこの問題に出くわすことは滅多にないですが、万一のために知っておくことは大切です。 少なくとも、なぜそのようなエラーが発生するのかを理解して回避できます。 カスケードの振る舞いを変える

    As described in the section on cascading updates, the primary mechanism to control the way updates and deletes cascade from one association to another is the static belongsTo property.

    However, the ORM DSL gives you complete access to Hibernate's transitive persistence capabilities using the cascade attribute.
    しかし、ORM DSLでは、Hibernateの連鎖的な永続化機能へのcascade属性を使った完全なアクセスを提供しています。

    Valid settings for the cascade attribute include:

    • merge - merges the state of a detached association
    • save-update - cascades only saves and updates to an association
    • delete - cascades only deletes to an association
    • lock - useful if a pessimistic lock should be cascaded to its associations
    • refresh - cascades refreshes to an association
    • evict - cascades evictions (equivalent to discard() in GORM) to associations if set
    • all - cascade all operations to associations
    • all-delete-orphan - Applies only to one-to-many associations and indicates that when a child is removed from an association then it should be automatically deleted. Children are also deleted when the parent is.

    • merge - デタッチされた関連の状態をマージする
    • save-update - saveとupdateのみを関連先にカスケードする
    • delete - deleteのみを関連先にカスケードする
    • lock - 悲観的ロックを関連先にカスケードしたいときに役立つ
    • refresh - refreshを関連先にカスケードする
    • evict - これをセットすると、evict(GORMでのdiscard()に相当)を関連先にカスケードする
    • all - すべての 操作を関連先にカスケードする
    • all-delete-orphan - 1対多関連にのみ適用する。子要素を関連から取り除いたときに自動的にその子要素を削除することを意味する。親が削除されたときは、子要素すべてが削除される。

    It is advisable to read the section in the Hibernate documentation on transitive persistence to obtain a better understanding of the different cascade styles and recommendations for their usage

    To specify the cascade attribute simply define one or more (comma-separated) of the aforementioned settings as its value:

    class Person {

    String firstName

    static hasMany = [addresses: Address]

    static mapping = { addresses cascade: "all-delete-orphan" } }

    class Address {
        String street
        String postCode
    } Hibernateのカスタム型

    You saw in an earlier section that you can use composition (with the embedded property) to break a table into multiple objects. You can achieve a similar effect with Hibernate's custom user types. These are not domain classes themselves, but plain Java or Groovy classes. Each of these types also has a corresponding "meta-type" class that implements org.hibernate.usertype.UserType.
    以前のセクションで、1つのテーブルに対して複数のオブジェクトを対応付けるために、embeddedプロパティによるコンポジションが使えることを説明しました。 Hibernateのカスタム型を利用すると同じようなことができます。 カスタム型自体はドメインクラスではなく、普通のJavaやGroovyクラスです。 また、それぞれのカスタム型には対応する「メタ型(meta-type)」クラスがあります。メタ型クラスはorg.hibernate.usertype.UserTypeインタフェースを実装します。

    The Hibernate reference manual has some information on custom types, but here we will focus on how to map them in Grails. Let's start by taking a look at a simple domain class that uses an old-fashioned (pre-Java 1.5) type-safe enum class:
    カスタム型についての情報はHibernateリファレンスマニュアルにあります。 ここではそれをGrails上でどのようにマッピングするかに焦点を絞ります。 (Java1.5以前の)昔ながらのタイプセーフenumクラスを使ったシンプルなドメインクラスをみてみましょう:

    class Book {

    String title String author Rating rating

    static mapping = { rating type: RatingUserType } }

    All we have done is declare the rating field the enum type and set the property's type in the custom mapping to the corresponding UserType implementation. That's all you have to do to start using your custom type. If you want, you can also use the other column settings such as "column" to change the column name and "index" to add it to an index.
    ratingフィールドをenum型として宣言し、カスタムマッピングでそのプロパティの型をUserType実装型にマッピングしています。 カスタム型に必要な設定はこれだけですが、必要であれば、カラム名を変更する「column」やインデックスを追加する「index」のような他のカラムの設定を使うこともできます。

    Custom types aren't limited to just a single column - they can be mapped to as many columns as you want. In such cases you explicitly define in the mapping what columns to use, since Hibernate can only use the property name for a single column. Fortunately, Grails lets you map multiple columns to a property using this syntax:
    カスタム型は単一カラム用に制限されているわけではありません。必要な分の複数カラムに対してマッピングできます。 単一カラムの場合はHibernateはプロパティ名を利用できますが、複数カラムの場合はどのカラムを使うのかmappingで明示的に定義する必要があります:

    class Book {

    String title Name author Rating rating

    static mapping = { author type: NameUserType, { column name: "first_name" column name: "last_name" } rating type: RatingUserType } }

    The above example will create "first_name" and "last_name" columns for the author property. You'll be pleased to know that you can also use some of the normal column/property mapping attributes in the column definitions. For example:
    上の例では、authorプロパティに対して、「first_name」と「last_name」という2つのカラムが作成されます。 嬉しいことに、このカラム定義において、通常のカラム/プロパティのマッピング属性がいくつか使えます。 例えば:

    column name: "first_name", index: "my_idx", unique: true

    The column definitions do not support the following attributes: type, cascade, lazy, cache, and joinTable.
    このカラム定義では次の属性はサポートされていません: type, cascade, lazy, cache, joinTable

    One thing to bear in mind with custom types is that they define the SQL types for the corresponding database columns. That helps take the burden of configuring them yourself, but what happens if you have a legacy database that uses a different SQL type for one of the columns? In that case, override the column's SQL type using the sqlType attribute:
    カスタム型について覚えておくべきことの1つは、対応するデータベースのカラムの SQLデータ型 があらかじめ決められていることです。 これによって自分で設定する負担が低減されます。しかし、カスタム型の想定とは異なるSQLデータ型が使われているレガシーデータベース上では、どうなってしまうのでしょうか? そのような場合は、sqlType属性を使ってそのカラムのSQLデータ型を上書きしてください:

    class Book {

    String title Name author Rating rating

    static mapping = { author type: NameUserType, { column name: "first_name", sqlType: "text" column name: "last_name", sqlType: "text" } rating type: RatingUserType, sqlType: "text" } }

    Mind you, the SQL type you specify needs to still work with the custom type. So overriding a default of "varchar" with "text" is fine, but overriding "text" with "yes_no" isn't going to work.
    指定したSQLデータ型とカスタム型に整合性が必要なことに注意してください。 デフォルトの「varchar」を「text」に上書きするのは良いですが、「text」を「yes_no」に上書きしてもうまく動きません。 派生プロパティ

    A derived property is one that takes its value from a SQL expression, often but not necessarily based on the value of one or more other persistent properties. Consider a Product class like this:
    派生プロパティはSQL式によって値が定まるプロパティです。 しかし、必ずしも他の1つ以上の永続化プロパティの値に基づいている必要はありません。 次のようなProductクラスを考えます:

    class Product {
        Float price
        Float taxRate
        Float tax

    If the tax property is derived based on the value of price and taxRate properties then is probably no need to persist the tax property. The SQL used to derive the value of a derived property may be expressed in the ORM DSL like this:
    もしtaxプロパティがpricetaxRateプロパティの値に基づいて算出されているなら、おそらくtaxプロパティを永続化する必要はないでしょう。 派生プロパティの算出に使われるSQLは、ORM DSLで次のように表すことができます:

    class Product {
        Float price
        Float taxRate
        Float tax

    static mapping = { tax formula: 'PRICE * TAX_RATE' } }

    Note that the formula expressed in the ORM DSL is SQL so references to other properties should relate to the persistence model not the object model, which is why the example refers to PRICE and TAX_RATE instead of price and taxRate.
    ORM DSLで表された式はSQLであるため、他のプロパティへの参照はオブジェクトモデルではなくデータベース上の永続化モデルの方に合わせることに注意してください。 サンプルコード上でpricetaxRateではなく、PRICETAX_RATEとなっているのはそのためです。

    With that in place, when a Product is retrieved with something like Product.get(42), the SQL that is generated to support that will look something like this:

        product0_.id as id1_0_,
        product0_.version as version1_0_,
        product0_.price as price1_0_,
        product0_.tax_rate as tax4_1_0_,
        product0_.PRICE * product0_.TAX_RATE as formula1_0_
        product product0_

    Since the tax property is derived at runtime and not stored in the database it might seem that the same effect could be achieved by adding a method like getTax() to the Product class that simply returns the product of the taxRate and price properties. With an approach like that you would give up the ability query the database based on the value of the tax property. Using a derived property allows exactly that. To retrieve all Product objects that have a tax value greater than 21.12 you could execute a query like this:
    taxプロパティは実行時に算出されデータベース上には格納されないため、ProductクラスにgetTax()のようなメソッドを追加して、単純にtaxRatepriceプロパティの積を返すようにすることで、同じ結果を達成できるようにみえるかもしれません。 しかし、そのようなアプローチでは、taxプロパティの値に基づいてデータベースを検索する能力を放棄することになります。 派生プロパティを使えばそれが可能です。 たとえば、taxの値が21.12以上のすべてのProductオブジェクトを取得するために、 次のようなクエリを実行できます:


    Derived properties may be referenced in the Criteria API:

    Product.withCriteria {
        gt 'tax', 21.12f

    The SQL that is generated to support either of those would look something like this:

        this_.id as id1_0_,
        this_.version as version1_0_,
        this_.price as price1_0_,
        this_.tax_rate as tax4_1_0_,
        this_.PRICE * this_.TAX_RATE as formula1_0_
        product this_
        this_.PRICE * this_.TAX_RATE>?

    Because the value of a derived property is generated in the database and depends on the execution of SQL code, derived properties may not have GORM constraints applied to them. If constraints are specified for a derived property, they will be ignored.
    派生プロパティの値はデータベース上で生成されたものでSQLコードの実行に依存するため、派生プロパティにはGORMの制約を適用できません。 もし派生プロパティに対して制約が指定されても無視されます。 命名規則のカスタマイズ

    By default Grails uses Hibernate's ImprovedNamingStrategy to convert domain class Class and field names to SQL table and column names by converting from camel-cased Strings to ones that use underscores as word separators. You can customize these on a per-class basis in the mapping closure but if there's a consistent pattern you can specify a different NamingStrategy class to use.
    GrailsはデフォルトでHibernateのImprovedNamingStrategyを使って、キャメルケースからアンダースコア区切りに変換することで、ドメインクラスのクラス名とフィールド名をSQLのテーブル名とカラム名に変換します。 テーブル名やカラム名はmappingクロージャでクラスごとにカスタマイズできますが、もし一貫した命名規則が存在するのであれば、異なるNamingStrategyクラスを使うように指定できます。

    Configure the class name to be used in grails-app/conf/DataSource.groovy in the hibernate section, e.g.

    dataSource {
        pooled = true
        dbCreate = "create-drop"

    hibernate { cache.use_second_level_cache = true … naming_strategy = com.myco.myproj.CustomNamingStrategy }

    You can also specify the name of the class and it will be loaded for you:

    hibernate {
        naming_strategy = 'com.myco.myproj.CustomNamingStrategy'

    A third option is to provide an instance if there is some configuration required beyond calling the default constructor:

    hibernate {
        def strategy = new com.myco.myproj.CustomNamingStrategy()
        // configure as needed
        naming_strategy = strategy

    You can use an existing class or write your own, for example one that prefixes table names and column names:
    既存のクラスを使うか、自分で書くことができます。 たとえば、テーブル名とカラム名の頭に文字列を追加するには以下のようなクラスを用意します:

    package com.myco.myproj

    import org.hibernate.cfg.ImprovedNamingStrategy import org.hibernate.util.StringHelper

    class CustomNamingStrategy extends ImprovedNamingStrategy {

    String classToTableName(String className) { "table_" + StringHelper.unqualify(className) }

    String propertyToColumnName(String propertyName) { "col_" + StringHelper.unqualify(propertyName) } }

    6.5.3 デフォルトソート順

    You can sort objects using query arguments such as those found in the list method:

    def airports = Airport.list(sort:'name')

    However, you can also declare the default sort order for a collection in the mapping:

    class Airport {
        static mapping = {
            sort "name"

    The above means that all collections of Airport instances will by default be sorted by the airport name. If you also want to change the sort order , use this syntax:
    上記はすべてのAirportのコレクションがデフォルトで空港名によってソートされることを意味します。 もしソート 順序 を変えたいなら、次のシンタックスを使います:

    class Airport {
        static mapping = {
            sort name: "desc"

    Finally, you can configure sorting at the association level:

    class Airport {
        static hasMany = [flights: Flight]

    static mapping = { flights sort: 'number', order: 'desc' } }

    In this case, the flights collection will always be sorted in descending order of flight number.

    These mappings will not work for default unidirectional one-to-many or many-to-many relationships because they involve a join table. See this issue for more details. Consider using a SortedSet or queries with sort parameters to fetch the data you need.
    これらのマッピングはデフォルトの単方向1対多/多対多関連では動作しません。結合テーブルが使われているためです。 より詳しくは、このチケットを参照してください。 それらのソートされたデータを取得するには、SortedSetやソートパラメータを指定したクエリを使うことを検討してください。

    6.6 プログラマチックトランザクション

    Grails is built on Spring and uses Spring's Transaction abstraction for dealing with programmatic transactions. However, GORM classes have been enhanced to make this simpler with the withTransaction method. This method has a single parameter, a Closure, which has a single parameter which is a Spring TransactionStatus instance.
    GrailsはSpringをベースに構築されていて、プログラマチックトランザクションを扱うためにSpringのトランザクション抽象を使います。 と言っても、withTransactionメソッドを使ってシンプルに利用できるようにGORMクラスが拡張されています。 このメソッドはクロージャを1つ引数に取ります。このクロージャはTransactionStatusインスタンスを引数に取ります。

    Here's an example of using withTransaction in a controller methods:


    def transferFunds() {
        Account.withTransaction { status ->
            def source = Account.get(params.from)
            def dest = Account.get(params.to)

    def amount = params.amount.toInteger() if (source.active) { if (dest.active) { source.balance -= amount dest.amount += amount } else { status.setRollbackOnly() } } } }

    In this example we rollback the transaction if the destination account is not active. Also, if an unchecked Exception or Error (but not a checked Exception, even though Groovy doesn't require that you catch checked exceptions) is thrown during the process the transaction will automatically be rolled back.
    この例では、送金先口座が有効ではない場合に、トランザクションをロールバックします。 また、もし非チェック例外であるRuntimeExceptionErrorがトランザクション処理中にスローされた場合も、自動的にロールバックされます。 (Groovyはチェック例外のcatchを必須としていないため、チェック例外と非チェック例外の区別が曖昧になりがちですが)チェック例外であるExceptionの場合にはロールバックされません。

    You can also use "save points" to rollback a transaction to a particular point in time if you don't want to rollback the entire transaction. This can be achieved through the use of Spring's SavePointManager interface.

    The withTransaction method deals with the begin/commit/rollback logic for you within the scope of the block.

    6.7 GORMと制約

    Although constraints are covered in the Validation section, it is important to mention them here as some of the constraints can affect the way in which the database schema is generated.

    Where feasible, Grails uses a domain class's constraints to influence the database columns generated for the corresponding domain class properties.

    Consider the following example. Suppose we have a domain model with the following properties:

    String name
    String description

    By default, in MySQL, Grails would define these columns as

    ColumnData Type

    But perhaps the business rules for this domain class state that a description can be up to 1000 characters in length. If that were the case, we would likely define the column as follows if we were creating the table with an SQL script.
    しかし、このドメインクラスに対するビジネスルールでは、descriptionは1000文字まで入力したいかもしれません。 その場合、 もし SQLスクリプトでテーブルを作成しているなら、たぶん次のようにカラムを定義するでしょう。

    ColumnData Type

    Chances are we would also want to have some application-based validation to make sure we don't exceed that 1000 character limit before we persist any records. In Grails, we achieve this validation with constraints. We would add the following constraint declaration to the domain class.
    ひょっとすると、レコードに永続化する 前に 1000文字の上限を超えないか確認できるように、アプリケーションベースのバリデーションも欲しくなるかもしれません。 Grailsではこのバリデーションは制約で達成できます。 次のような制約の宣言をドメインクラスに追加します。

    static constraints = {
        description maxSize: 1000

    This constraint would provide both the application-based validation we want and it would also cause the schema to be generated as shown above. Below is a description of the other constraints that influence schema generation.
    この制約は、欲しかったアプリケーションベースのバリデーションを提供するだけでなく、前述したような1000文字分を格納できるスキーマも生成してくれます。 以下は、スキーマ生成に影響するその他の制約の説明です。

    h4. Constraints Affecting String Properties


    If either the maxSize or the size constraint is defined, Grails sets the maximum column length based on the constraint value.

    In general, it's not advisable to use both constraints on the same domain class property. However, if both the maxSize constraint and the size constraint are defined, then Grails sets the column length to the minimum of the maxSize constraint and the upper bound of the size constraint. (Grails uses the minimum of the two, because any length that exceeds that minimum will result in a validation error.)

    一般的に、maxSize制約とsize制約を同時に同じドメインクラスのプロパティに適用することは推奨されません。 しかし、もしそれらが同時に定義された場合には、GrailsはmaxSize制約の値とsize制約の上限値の小さい方の値をカラムの長さとしてセットします。 (Grailsがその2つの値の最小値を利用するのは、その最小値を超える長さであれば結局バリデーションエラーになるためです。)

    If the inList constraint is defined (and the maxSize and the size constraints are not defined), then Grails sets the maximum column length based on the length of the longest string in the list of valid values. For example, given a list including values "Java", "Groovy", and "C++", Grails would set the column length to 6 (i.e., the number of characters in the string "Groovy").

    inList制約が定義された場合(maxSizesize制約は定義されていないとする)、Grailsは有効な値のリストの中でもっとも長い文字列長を元にカラムの長さをセットします。 例えば、"Java", "Groovy", "C++"を含むリストが与えられた場合、Grailsはカラムの長さを6(すなわち、"Groovy"の文字数)にセットします。

    h4. Constraints Affecting Numeric Properties


    If the max, min, or range constraint is defined, Grails attempts to set the column precision based on the constraint value. (The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.)
    maxmin, range制約が定義されると、Grailsは制約の値に基づいた精度(有効桁数)をカラムにセットしようと試みます。 (その試みが成功するかどうかは、Hibernateが裏にあるDBMSとどのように相互作用するかに大きく依存します。)

    In general, it's not advisable to combine the pair min/max and range constraints together on the same domain class property. However, if both of these constraints is defined, then Grails uses the minimum precision value from the constraints. (Grails uses the minimum of the two, because any length that exceeds that minimum precision will result in a validation error.)

    一般的に、min/maxのペアとrange制約を同時に同一のドメインクラスプロパティに適用することは推奨されません。 しかし、もしそれらが同時に定義された場合には、Grailsは制約から算出される精度の内で最も小さい精度を使います。 (Grailsがそれらの最小精度を利用するのは、その最小精度を超える場合は結局バリデーションエラーになるためです。)

    If the scale constraint is defined, then Grails attempts to set the column scale based on the constraint value. This rule only applies to floating point numbers (i.e., java.lang.Float, java.Lang.Double, java.lang.BigDecimal, or subclasses of java.lang.BigDecimal). The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.
    scale制約が定義されると、Grailsは制約の値に基づいたscaleをカラムにセットしようと試みます。 このルールは浮動小数点型(すなわち、java.lang.Float, java.Lang.Double, java.lang.BigDecimal、または、java.lang.BigDecimalのサブクラスのいずれか)の場合にのみ適用されます。 その試みが成功するかどうかは、Hibernateが裏にあるDBMSとどのように相互作用するかに大きく依存します。

    The constraints define the minimum/maximum numeric values, and Grails derives the maximum number of digits for use in the precision. Keep in mind that specifying only one of min/max constraints will not affect schema generation (since there could be large negative value of property with max:100, for example), unless the specified constraint value requires more digits than default Hibernate column precision is (19 at the moment). For example:
    max/minrange制約では、最大/最小の数値を定義します。そして、そこからGrailsは精度として利用するための最大桁数を算出します。 指定された制約値がHibernateのデフォルトカラム精度(現在は19)よりも多くの桁数を必要とする場合を除いて、min制約とmax制約のどちらかひとつだけを指定しても、スキーマ生成には影響しないことを覚えておいてください。 (なぜなら、例えばmax:100を指定したとしても、大きな負の数も許容されるため、必要な精度は確定できないからです。)


    someFloatValue max: 1000000, scale: 3

    would yield:

    someFloatValue DECIMAL(19, 3) // precision is default


    someFloatValue max: 12345678901234567890, scale: 5

    would yield:

    someFloatValue DECIMAL(25, 5) // precision = digits in max + scale


    someFloatValue max: 100, min: -100000

    would yield:

    someFloatValue DECIMAL(8, 2) // precision = digits in min + default scale

    7 Webレイヤ

    7.1 コントローラ

    A controller handles requests and creates or prepares the response. A controller can generate the response directly or delegate to a view. To create a controller, simply create a class whose name ends with Controller in the grails-app/controllers directory (in a subdirectory if it's in a package).

    The default URL Mapping configuration ensures that the first part of your controller name is mapped to a URI and each action defined within your controller maps to URIs within the controller name URI.
    URL マッピングのデフォルト設定では、Controllerの前に付けた名称がベースのURIにマップされ、コントローラに定義したそれぞれのアクション名称がコントローラ名称と繫がれてURIをマップします。

    7.1.1 コントローラとアクションの理解


    Controllers can be created with the create-controller or generate-controller command. For example try running the following command from the root of a Grails project:

    grails create-controller book

    The command will create a controller at the location grails-app/controllers/myapp/BookController.groovy:

    package myapp

    class BookController {

    def index() { } }

    where "myapp" will be the name of your application, the default package name if one isn't specified.

    BookController by default maps to the /book URI (relative to your application root).
    デフォルトでは、BookControllerは、URIが /bookとなります。(アプリケーションのコンテキストルートからの相対パス)

    The create-controller and generate-controller commands are just for convenience and you can just as easily create controllers using your favorite text editor or IDE create-controllergenerate-controllerコマンドは、簡単にコントローラを生成する便利なコマンドですが、IDEやテキストエディタの機能でクラスを作成してもかまいません。


    A controller can have multiple public action methods; each one maps to a URI:

    class BookController {

    def list() {

    // do controller logic // create model

    return model } }

    This example maps to the /book/list URI by default thanks to the property being named list.


    In earlier versions of Grails actions were implemented with Closures. This is still supported, but the preferred approach is to use methods.

    Leveraging methods instead of Closure properties has some advantages:
    • Memory efficient
    • Allow use of stateless controllers (singleton scope)
    • You can override actions from subclasses and call the overridden superclass method with super.actionName()
    • Methods can be intercepted with standard proxying mechanisms, something that is complicated to do with Closures since they're fields.

    • メモリ効率
    • ステートレスコントローラの使用 (シングルトンスコープ指定)
    • サブクラスでのアクションのオーバーライドが可能。スーパークラスのアクションメソッド呼び出しが可能。super.actionName()
    • クロージャはフィールドのため複雑だった、スタンダードなプロキシを使用したメソッドのインターセプトが可能。

    If you prefer the Closure syntax or have older controller classes created in earlier versions of Grails and still want the advantages of using methods, you can set the grails.compile.artefacts.closures.convert property to true in BuildConfig.groovy:
    クロージャを使用したい場合や、旧バージョンで作られたコントローラを使用しながら、メソッドの利点も欲しい場合は、BuildConfig.groovyに、 grails.compile.artefacts.closures.convertを定義します:
    grails.compile.artefacts.closures.convert = true

    and a compile-time AST transformation will convert your Closures to methods in the generated bytecode.

    If a controller class extends some other class which is not defined under the grails-app/controllers/ directory, methods inherited from that class are not converted to controller actions. If the intent is to expose those inherited methods as controller actions the methods may be overridden in the subclass and the subclass method may invoke the method in the super class.


    A controller has the concept of a default URI that maps to the root URI of the controller, for example /book for BookController. The action that is called when the default URI is requested is dictated by the following rules:
    コントローラのルートURIににデフォルトURIをマップする概念をもっています。例としてBookControllerの場合は /bookになります。デフォルトURIが呼ばれたときに呼ばれるアクションは以下のルールになっています:
    • If there is only one action, it's the default
    • If you have an action named index, it's the default
    • Alternatively you can set it explicitly with the defaultAction property:

    • アクションが1つの場合は、それがデフォルトになります。
    • indexという名称のアクションがある場合は、それがデフォルトになります。
    • defaultActionを定義して指定できます。

    static defaultAction = "list"

    7.1.2 コントローラとスコープ


    Scopes are hash-like objects where you can store variables. The following scopes are available to controllers:
    • servletContext - Also known as application scope, this scope lets you share state across the entire web application. The servletContext is an instance of ServletContext
    • session - The session allows associating state with a given user and typically uses cookies to associate a session with a client. The session object is an instance of HttpSession
    • request - The request object allows the storage of objects for the current request only. The request object is an instance of HttpServletRequest
    • params - Mutable map of incoming request query string or POST parameters
    • flash - See below

    • servletContext - webアプリケーションの全体にわたってスコープを共有するアプリケーションスコープです。ServletContextのインスタンスです。
    • session - セッションは、通常クッキーを使用してリクエストを行ったクライアントとの連携をして、ステートを保持します。HttpSessionのインスタンスです。
    • request - リクエストオブジェクトはリクエスト時のみオブジェクトを保持するオブジェクトです。HttpServletRequestのインスタンスです。
    • params - 受け取ったリクエストクエリー文字列または、POSTパラメータを保持するミュータブルマップです。
    • flash - 以下を参照


    Scopes can be accessed using the variable names above in combination with Groovy's array index operator, even on classes provided by the Servlet API such as the HttpServletRequest:
    以下のようにスコープはGroovyの配列インデクスオペレータで、変数の名称を指定して参照することができます。HttpServletRequestにあるような、Servlet APIの提供する変数に関しても同じようにアクセスできます

    class BookController {
        def find() {
            def findBy = params["findBy"]
            def appContext = request["foo"]
            def loggedUser = session["logged_user"]

    You can also access values within scopes using the de-reference operator, making the syntax even more clear:

    class BookController {
        def find() {
            def findBy = params.findBy
            def appContext = request.foo
            def loggedUser = session.logged_user

    This is one of the ways that Grails unifies access to the different scopes.


    Grails supports the concept of flash scope as a temporary store to make attributes available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirecting, for example:
    Grailsは、今回のリクエストと次のリクエストのみで値を一時的に保持する flashスコープをサポートしています。保持された内容は自動的に削除されます。リダイレクト等を行う前にメッセージを残す時などに使用できます。以下が例です。

    def delete() {
        def b = Book.get(params.id)
        if (!b) {
            flash.message = "User not found for id ${params.id}"
        … // remaining code

    When the list action is requested, the message value will be in scope and can be used to display an information message. It will be removed from the flash scope after this second request.

    Note that the attribute name can be anything you want, and the values are often strings used to display messages, but can be any object type.

    h4. Scoped Controllers


    Supported controller scopes are:
    • prototype (default) - A new controller will be created for each request (recommended for actions as Closure properties)
    • session - One controller is created for the scope of a user session
    • singleton - Only one instance of the controller ever exists (recommended for actions as methods)

    • prototype (デフォルト) - リクエスト毎にコントローラが生成されます。(クロージャでアクションを推奨)
    • session - ユーザのセッションを通して1個のコントローラが生成されます。
    • singleton - 1個のコントローラのみが存在する状態です。(メソッドでのアクションをお勧めします)

    To enable one of the scopes, add a static scope property to your class with one of the valid scope values listed above, for example
    スコープを定義するには、コントローラクラスに、static scope 変数で指定したいスコープを定義します。以下が例になります。

    static scope = "singleton"

    You can define the default strategy under in Config.groovy with the grails.controllers.defaultScope key, for example:

    grails.controllers.defaultScope = "singleton"

    Newly created applications have the grails.controllers.defaultScope property set in grails-app/conf/Config.groovy with a value of "singleton". You may change this value to any of the supported scopes listed above. If the property is not assigned a value at all, controllers will default to "prototype" scope.

    Use scoped controllers wisely. For instance, we don't recommend having any properties in a singleton-scoped controller since they will be shared for all requests. Setting a default scope other than prototype may also lead to unexpected behaviors if you have controllers provided by installed plugins that expect that the scope is prototype.
    コントローラのスコープは使用状況を考えてお使いください。例えば、シングルトンのコントローラは、_全ての_リクエストで共有されるためプロパティを持つべきではありません。デフォルトで定義されているスコープのprototype を変更することで、プラグインなどで提供されたコントローラがprotopypeを前提で実装されている場合があるので注意しましょう

    7.1.3 モデルとビュー


    A model is a Map that the view uses when rendering. The keys within that Map correspond to variable names accessible by the view. There are a couple of ways to return a model. First, you can explicitly return a Map instance:

    def show() {
        [book: Book.get(params.id)]

    The above does not reflect what you should use with the scaffolding views - see the scaffolding section for more details.

    If no explicit model is returned the controller's properties will be used as the model, thus allowing you to write code like this:

    class BookController {

    List books List authors

    def list() { books = Book.list() authors = Author.list() } }

    This is possible due to the fact that controllers are prototype scoped. In other words a new controller is created for each request. Otherwise code such as the above would not be thread-safe, and all users would share the same data.

    In the above example the books and authors properties will be available in the view.
    上記の例では、 プロパティのbookauthorsがビューで参照できます。

    A more advanced approach is to return an instance of the Spring ModelAndView class:

    import org.springframework.web.servlet.ModelAndView

    def index() { // get some books just