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 イントロダクション
- 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フレームワークのトランザクション概念によるサービスレイヤのトランザクション
1.1 Grails 2.3の新機能
依存管理の向上
BuildConfig
:BuildConfig
で設定をすることでどちらのエンジンを使用するか変更可能です。grails.project.dependency.resolver = "maven" // or ivy
データバインダー
- Custom date formats on a per field basis using BindingFormat
- User defined data converters using ValueConverter
- User defined formatted data converters using BindingFormat and FormattedValueConverter
- Custom binding on a per class basis using BindUsing
- Custom binding on a per field basis using BindUsing
- By default all blank and empty Strings will be converted to null during data binding (configurable)
- フィールドごとのカスタムデータフォーマット - BindingFormat
- ユーザ定義可能なデータコンバーター - ValueConverter
- ユーザ定義フォーマットデータコンバーター - BindingFormat FormattedValueConverter
- クラスごとのカスタムバインディング - BindUsing
- フィールドごとのカスタムバインディング - BindUsing
- デフォルトで全ての空文字列とブランクはデータバインディングでnullに変換されます(設定可能)
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.groovy
の grails.databinding.useSpringBinder
プロパティを true
にすることで以前のデータバインダーに変更することができます。 以前のバインダーは今回実装された新機能には対応していません。リクエストボディをコマンドオブジェクトにバインド
コントローラアクションがコマンドオブジェクトを受け取れる状態でリクエストがボディを含んでいる場合、ボディの内容はパースされコマンドオブジェクトにデータバインドされます。この機能は、リクエストの内容が対象のコマンドオブジェクトに対応したJSONまたXMLのボディを含んでいる処理を単純化します。 詳細は Command Objects のドキュメントを参照してください。
ドメインクラスをコマンドオブジェクトとして使用する際の振る舞い
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 のドキュメントを参照してください。
フォーク実行
BuildConfig
: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への設定 ]
テストランナーデーモン
restart-daemon
command from interactive mode:restart-daemon
コマンド実行すると再起動できます。$ grails> restart-daemon
サーバサイドRESTの向上
- 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コントローラのスカッフォルディング
スカッフォルディング2.0プラグイン
URLマッピングのリダイレクト指定
class UrlMappings { static mappings = { "/viewBooks"(redirect: '/books/list') "/viewAuthors"(redirect: [controller: 'author', action: 'list']) "/viewPublishers"(redirect: [controller: 'publisher', action: 'list', permanent: true])// … } }
非同期サポート
import static grails.async.Promises.* … def index() { tasks books: Book.async.list(), totalBooks: Book.async.count(), otherValue: { // do hard work } }
エンコーディング / エスケーピングの向上
- 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ページ内の全てのデータに対して安全と判断しない場合の自動エンコーディング
Hibernate 3と4をサポート
コントローラ例外ハンドリング
// grails-app/controllers/demo/DemoController.groovy package democlass 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'] } }
コントローラネームスペース
// grails-app/controllers/com/app/reporting/AdminController.groovy package com.app.reportingclass AdminController {
static namespace = 'reports'
// … }
// grails-app/controllers/com/app/security/AdminController.groovy package com.app.securityclass 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>
詳しくは、 ドキュメント を参照してください。
コマンドライン
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
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
という名称のサービスが存在した場合、それぞれのビーン名称は、 publishingUtilitiesAuthorService
と bookUtilitiesAuthorService
になります。
もし他のサービス名称がプラグインが提供したサービスの名称に衝突しない場合は、自動的にプリフィックスの無いビーンエイリアスを生成して、プリフィックスの存在するビーンを参照します。
アプリケーションで直接提供するサービスアーティファクトには、プリフィックスは追加されません。
依存注入とサービスも参照。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.enabled
が true
に設定されている場合、テーブル名称にプラグイン名のプリフィックスが追加されます。例として、 PublishingUtilities
プラグインが提供した Book
とい名称のドメインクラスであれば、テーブル名称が PUBLISHING_UTILITIES_BOOK
となります。
plugin
attribute to indicate that the controller referenced in the mapping is provided by a particular plugin.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' } }
plugin
属性を使用します。<g:link controller="user" plugin="springSecurity">Manage Users</g:link>
class DemoController { def index() { redirect controller: 'user', action: 'list', plugin: 'springSecurity' } }
フォークされたTomcat実行 Forked Tomcat Execution
- 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アプリケーションのデプロイを可能にします。
クライテリアクエリーでのSQLプロジェクション SQL Projections In Criteria Queries
// 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] } }
Groovy 2
1.3 Grails 2.1の新機能
Maven機能向上 / Maven マルチモジュールビルド対応 Maven Improvements / Multi Module Build Support
pom.xml
file:
<dependency> <groupId>org.grails.plugins</groupId> <artifactId>hibernate</artifactId> <version>2.1.0</version> <type>zip</type> <scope>compile</scope> </dependency>
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ラッパー 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コマンドエイリアス 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.
新たなGORMメソッド 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の新機能
1.4.1 開発環境機能
インタラクティブモードとコンソールの強化 Interactive Mode and Console Enhancements
リロードエージェント Reloading Agent
新テストレポートとドキュメントテンプレート New Test Report and Documentation Templates
プロジェクトドキュメントでの目次 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
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データベースとDBコンソール H2 Database and Console
プラグイン使用数等のトラッキング機能 Plugin Usage Tracking
依存管理機能改善 Dependency Resolution Improvements
- 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"
}
settings.groovy
settings.groovy
に設定することで、全てのプロジェクトのivyキャッシュディレクトリを変更できます。
grails.dependency.cache.dir = "${userHome}/.ivy2/cache"
- リポジトリの引継を完全に無効にできます(他のプラグインで定義されている場合等):
grails.project.dependency.resolution = {repositories { inherits false // Whether to inherit repository definitions from plugins … } … }
- チェックサムを無効にできます:
grails.project.dependency.resolution = {
checksums false // whether to verify checksums or not
}
1.4.2 コア機能
バイナリプラグイン Binary Plugins
Groovy 1.8 Groovy 1.8
Spring 3.1 プロファイルサポート Spring 3.1 Profile Support
1.4.3 Web機能
コントローラのアクションにメソッドを利用 Controller Actions as Methods
// メソッドのアクション (action as a method) def index() {} // クロージャのアクション (action as a closure) def index = {
}
アクションに引数を指定してバインド Binding Primitive Method Action Arguments
<g:form name="myForm" action="save"> <input name="name" /> <input name="age" /> </g:form>
def save(String name, int age) { // remaining }
静的リソース抽象化 Static Resource Abstraction
サーブレット3.0の非同期処理 Servlet 3.0 Async Features
def index() { def ctx = startAsync() ctx.start { new Book(title:"The Stand").save() render template:"books", model:[books:Book.list()] ctx.complete() } }
リンク生成API Link Generation API
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:LinkGenerator
クラスが追加されました。コントローラのコンテキスト以外のどこからでも使用できます。例としてサービス、バックグラウンド処理、非同期タスク、リクエスト以外の場所でリンクが生成できます。LinkGenerator grailsLinkGeneratordef generateLink() { grailsLinkGenerator.link(controller:"book", action:"list") }
ページレンダリングAPI Page Rendering API
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 groovyPageRenderervoid welcomeUser(User user) { def contents = groovyPageRenderer.render(view:"/emails/welcomeLetter", model:[user: user]) sendEmail { to user.email body contents } }
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
filter1(actionExclude: 'log*') { before = { // … } } filter2(controllerExclude: 'auth') { before = { // … } }filter3(uriExclude: '/secure*') { before = { // … } }
パフォーマンスの向上 Performance Improvements
HTML5スカッフォルド HTML5 Scaffolding
jQueryがデフォルトになりました jQuery by Default
簡単な日付解析 Easy Date Parsing
date
method has been added to the params
object to allow easy, null-safe parsing of dates:params
オブジェクトのnullセーフメソッドに日付用のdate
が追加されました。
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')
URLフォーマットのカスタマイズ
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.groovygrails.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.groovypackage 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.groovybeans = { "${grails.web.UrlConverter.BEAN_NAME}"(com.myapplication.MyUrlConverterImpl) }
Webフローのインプットとアウトプット Web Flow input and output
1.4.4 永続化機能
GORM API The GORM API
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.GormStaticApi
、 GormInstanceApi
、 GormValidationApi
というクラスに置き換えられたことによって、全てのドメインのバイトコードレベルに注入されます。この実装でIDEでのコード補完、Javaとの統合、様々なデータストアへのGORM実装への可能性が向上しました。DetachedクライテリアとWhereクエリー 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.
新findOrCreateとfindOrSaveメソッド New findOrCreate and findOrSave Methods
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
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
DataSource.groovy
and declare one or more datasources a particular domain uses by default:class ZipCode {String code
static mapping = { datasource 'ZIP_CODES' } }
def zipCode = ZipCode.auditing.get(42)
データベースマイグレーション Database Migrations
データベースリバースエンジニアリング Database Reverse Engineering
Hibernate 3.6 Hibernate 3.6
Bagコレクション Bag Collections
Set
uniqueness or List
order.1.4.5 テスト機能
新ユニットテストのコンソール出力 New Unit Testing Console Output
新しいユニットテストAPI New Unit Testing API
import grails.test.mixin.TestFor@TestFor(SimpleController) class SimpleControllerTests { void testIndex() { controller.home()
assert view == "/simple/homePage" assert model.title == "Hello World" } }
GORMのユニットテスト Unit Testing GORM
インタラクティブモードで快速なユニットテストを Faster Unit Testing with Interactive Mode
Unit Test スカッフォルド Unit Test Scaffolding
2 スタートガイド
2.1 インストール必要条件
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:JAVA_HOME
が指定されている必要があります。一部のプラットフォームでは(OS Xの例で言うと)、自動的にJavaのインストール先を認識します。手動で定義する場合等、必要に応じて次のようにJavaの設定を行ってください。方法がわからない場合は、コチラの動画も参考にしてください。grailsexample.net
A JDK is required in your Grails development environment. A JRE is not sufficient.
JDKがGrailsの開発時に必須になります。JREでは十分ではありません。
export JAVA_HOME=/Library/Java/Home
export PATH="$PATH:$JAVA_HOME/bin"
2.2 ダウンロードとインストール
- 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 yourPATH
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 underMy 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を追加します。
grails -version
in the terminal window and see output similar to this:grails
と入力し実行することで下記のような出力がされれば、Grailsが正常に動作しています:
Grails version: 2.0.0
2.3 アプリケーション作成
grails
command which is used in the following manner:grails
コマンドの使用法に慣れておきましょう。grails [コマンド名]
grails create-app helloworld
cd helloworld
2.4 Hello Worldの例
helloworld
ディレクトリへ移動し、Grailsのインタラクティブコンソールを起動します:
$ cd helloworld
$ grails
grails> create-controller hello
create-*
commands. Type a few more letters of the command name and then <tab> again to finish.
cre
と入力し、そしてすべてのcreate-*
コマンド一覧を表示するために<tab>
を押します。
さらにいくつかのコマンド名を入力し、そして補完を完了するために<tab>
をもう1度押します。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のリファレンスページではより詳細な情報を提供しています。package helloworldclass HelloController {
def index() { render "Hello World!" } }
grails> run-app
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
の間で任意のポートを指定できます。
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アプリケーションが完成です。/<appname>/<controller>/<action>
の形式でコントローラ名、アクション名から構成されます。
/helloworld/hello/indexを通してHello Worldページにアクセスできますが、これはhello
がコントローラ名(クラス名からサフィックスのController
を削除して、最初の文字を小文字する)、index
がアクション名になります。
ですが、ここではアクション名を削除したURLでも同じページにアクセスできます。これはindex
が デフォルトアクション であるためです。
このデフォルトアクションの詳細はユーザガイドのコントローラとアクションセクションの最後を参照してください。
2.5 インタラクティブモードの利用
2.6 IDEの設定
IntelliJ IDEA
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
.grails integrate-with --intellij
コマンドを実行する必要がありません。Ultimate Editionでは、Grailsにネイティブ対応しています。プロジェクトを File -> New Project -> Create project
で開くだけで良いです。grails integrate-with --intellij
Eclipse
NetBeans
TextMate
grails integrate-with --textmate
mate .
2.7 Convention over Configuration 設定より規約
grails-app
- top level directory for Groovy sourcesconf
- Configuration sources.controllers
- Web controllers - The C in MVC.domain
- The application domain.i18n
- Support for internationalization (i18n).services
- The service layer.taglib
- Tag libraries.utils
- Grails specific utilities.views
- Groovy Server Pages - The V in MVC.scripts
- Gant scripts.src
- Supporting sourcesgroovy
- Other Groovy sourcesjava
- Other Java sourcestest
- Unit and integration tests.
grails-app
- Groovyのソースディレクトリの最上位conf
- 設定ソースcontrollers
- Webコントローラ - MVCのCdomain
- アプリケーションドメインi18n
- 国際化(i18n)のサポートservices
- サービス層taglib
- タグライブラリutils
- Grails特化なユーティリティviews
- Groovy Server Pagesscripts
- Gantスクリプトsrc
- サポートソースgroovy
- その他のGroovyのソースjava
- その他のJavaソースtest
- ユニットテストと統合テスト
2.8 アプリケーションの起動
grails run-app
server.port
argument:server.port
を指定して別のポートで起動することもできます。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
2.9 アプリケーションのテスト
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.create-*
コマンドは、自動的にユニットテストまたは統合テストをそれぞれtest/unit
またtest/integration
ディレクトリに生成します。スケルトンのテストのロジックは各自で実装してください。テストの詳細についてはTestingを参考にしてください。grails test-app
2.10 アプリケーションのデプロイ
grails war
target
directory which can then be deployed as per your container's instructions.target
ディレクトリ以下に生成されます。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:war
コマンドでは、環境がdevelopment
にオーバーライドされて、production
がデフォルトになります。他のスクリプトと同じく環境名を指定することで変更可能です。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 implicationsGrailsを本番運用する際はWARをデプロイしてください。run-appコマンドでの運用は基本的に自動リロードなどが設定されているため、パフォーマンスやスケーラビリティに影響します。
-server
option and with sufficient memory allocation. A good set of VM flags would be:-server
オプションと十分なメモリを割り当てて、Webコンテナを動作させましょう。JVM起動オプションの良い設定は次のようになります:-server -Xmx512M -XX:MaxPermSize=256m
2.11 サポートされている Java EE コンテナ
- 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 以降では不要です。
2.12 アプリケーション生成
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 アーテファクトの作成
These are just for your convenience and you can just as easily use an IDE or your favourite text editor.アーテファクト生成は便利機能です。IDEやテキストエディタを使用してもかまいません。
grails create-domain-class book
grails-app/domain/Book.groovy
such as:grails-app/domain/Book.groovy
に以下のようなドメインクラスが作成されます:class Book { }
create-*
commands that can be explored in the command line reference guide.create-*
コマンドがあります。詳しくはコマンドライン・リファレンス・ガイドを参照しましょう。To decrease the amount of time it takes to run Grails scripts, use the interactive mode.interactiveモードを使用することでGrailsスクリプトの起動時間を減らすことができます。
3 Grails下位バージョンからの更新
新データバインダー
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
依存性管理の変更
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 :: :::: WARNINGS :::::::::::::::::::::::::::::::::::::::::::::: :: 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:
grails.project.dependency.resolver="maven"
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.
テストでのフォーク実行
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 … ]
フォーク実行とリロードエージェント
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 ]
フォーク実行とリモートデバッグ
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 ...
コアプラグインのバージョン管理方法の変更とアップグレードコマンド
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:7.0.40.1'// 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.
エンコーディング・エスケーピング(XSS)の変更
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.
公式版では以下のドキュメントはこのページに存在しません。公式版で過去の更新注意点を確認する際には該当するバージョンのドキュメントを参照してください。
2.2以前(保存用)
公式版では以下のドキュメントはこのページに存在しません。公式版で過去の更新注意点を確認する際には該当するバージョンのドキュメントを参照してください。
- 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.environment
ビーンが自動追加されます。- ロギングDSLのパッケージが変更されたので正常にログ出力がされない場合があります。ログの設定を変更する必要があります。
- デフォルトのインメモリーデータベースがHSQLDBからH2へ変更になりました。使用している場合はデータソースの設定を変更するか、HSQLDBを依存管理に追加する必要があります。
release-plugin
command has been removed. You must now install the Release plugin and use its publish-plugin
command instead. release-plugin
コマンドが無くなります。代わりに、 Releaseプラグイン をインストールして、publish-plugin
コマンド を使用してください。
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()
を使用しましょう
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()
を使用してください。
- Prototypeを使用したAJAXタグは動作しません。必要であれば、Prototypeプラグインをインストールしてください。
<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プラグインはURL '/static'を追加します。それに応じたアクセスコントロールを更新する必要があります。
BuildConfig.groovy
.- 幾つかのプラグインは依存が見つからなかった際にインストールに失敗する場合があります。その場合は、プラグインがカスタムリポジトリURLを使用している可能性があるので、プロジェクトの
BuildConfig.groovy
に追加する必要があります。
- 抽象ドメインクラスの振る舞いが変更されました。使用している場合は、抽象クラスを'src/groovy'に移動するか、データベースのスキーマとデータを変更する必要があります。
- クライテリアクエリーのデフォルトがOUTER_JOINからINNER_JOINに変更になりました。幾つかの実装結果に影響が出る可能性があります。
- 存在しないプロパティが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回そしてビューがレンダリングされる直前など。- コントローラ内のパブリックメソッドはアクションとして扱われるようになります。アクションとして扱われたくないメソッドは、protectedまたは、privateに変更してください。
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
を継承しないようにしてください。
ant.echo()
, ant.input()
, etc. you might want to use alternative mechanisms for output.- Antタスクからの出力はデフォルトで隠すようになりました。
ant.echo()
,ant.input()
等をスクリプトで使用している場合は、出力用の代替機能を使用してください。
- ドメインプロパティでjava.net.URL型を使用している場合は、既存のデータで動作しません。シリアライゼーションの仕組みが変更になったようです。ドメインモデルとデータをStringに変更することを検討してください。
- Ivyのキャッシュ場所が変更になりました。古い場所を使用したい場合は、グローバル設定で変更することができます。ただし、1.3.x系と2.x系を平行利用する場合は問題が発生します。
- 多くのライブラリが新バージョンに変更されました。更新されたライブラリを使用している場合は変更が必要となります。
grails.web.JsonBuilder
and grails.web.OpenRicoBuilder
.- 次の非推奨クラスが削除されました:
grails.web.JsonBuilder
、grails.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
web.xmlテンプレートの内容変更 Changes to web.xml template
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
- 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) {}
HSQLDBからH2へ変更 HSQLDB Has Been Replaced With H2
grails.project.dependency.resolution = { inherits("global") { } repositories { grailsPlugins() grailsHome() grailsCentral() }dependencies { // HSQLDBの依存定義 (Add HSQLDB as a runtime dependency) runtime 'hsqldb:hsqldb:1.8.0.10' } }
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" } } }
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:byte[]
の扱いです。HSQLDBでのBLOBのデフォルトサイズは、大きいので大抵最大サイズを定義する必要が無かったかと思います。H2では最大サイズの初期値が255バイトになっているので、調整する必要があります。調整するには、 制約の maxSize
を byte[]
のプロパティに定義するだけです。class MyDomain { byte[] datastatic constraints = { data maxSize: 1024 * 1024 * 2 // 2MB } }
data
column set to BINARY(2097152)
by Hibernate.BINARY(2097152)
としてHibernateがセットします。抽象クラスの継承が変更になります Abstract Inheritance Changes
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 {
}
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.BOOK
テーブルが生成され、BOOKテーブルに Sellable
クラスのプロパティも含まれました。Grails 2.0からは、デフォルトのtable-per-hierarchy (クラス階層ごとのテーブル)継承ルールで、 BOOK
クラスの全てのプロパティが含まれた SELLABLE
テーブルが生成されます。- Move the abstract
Sellable
class into the src/groovy package. If theSellable
class is in thesrc/groovy
directory it will no longer be regarded as persistent. - 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).
- 抽象クラス
Sellable
をsrc/groovyに移動する。src/groovyに移動すれば永続化対象のクラスとしては認識しません。 - データベースマイグレーションプラグイン を使用して、データベースに適した変更を行う。(通常はルート抽象クラスのテーブル名称に変更すれば良いです。)
クライテリアクエリのデフォルトがINNER JOINになります Criteria Queries Default to INNER JOIN
存在しないプロパティの制約で例外を投げます Invalid Constraints Now Thrown an Exception
class Person { String name static constraints = { bad nullable:false // invalid property, no error thrown } }
ログでの慣習変更 Logging By Convention Changes
service
->services
controller
->controllers
tagLib
->taglib
(case change)bootstrap
->conf
dataSource
->conf
service
->services
controller
->controllers
tagLib
->taglib
(Lが小文字に)bootstrap
->conf
dataSource
->conf
log
property into artefacts at compile time.PrototypeからjQueryに変更 jQuery Replaces Prototype
web-app/js/prototype
directory if you want.Resourcesプラグイン 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
private
methods.private
にしてください。コマンドオブジェクト制約 Command Object Constraints
リダイレクトメソッド The redirect Method
redirect action: "next" if (response.committed) { // do something }
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:response.committed
プロパティがtrueを返すため if
ブロックが実行されます。Grails 1.4では、同等の動きをしないため、代わりに request
インスタンスの isRedirected()
メソッドを使用します。redirect action: "next" if (request.redirected) { // do something }
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
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:CONTENT_TYPE
ヘッダ)を評価しなくなりました。これにかわって、レスポンスのコンテントタイプ(ACCEPT
ヘッダまたはファイル拡張子)が排他的に処理を行います。これによって今までのアプリケーションのwithFormat
を使用してリクエストからXMLを読み込む等のコードは動作しなくなります。def processBook() { withFormat { xml { // read request XML } html { // read request parameters } } }
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
GrailsUnitTestCase
class hierarchy is still available for backwards compatibility, but it does not work with the new annotations.GrailsUnitTestCase
クラス階層をベースとした古いフレームワークも使用可能です。但し、新しい仕組みのアノテーションとは平行利用できません。- 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. - Add
@Mock
annotation for domain classes that must be mocked and usenew MyDomain().save()
in place ofmockDomain()
. - Replace references to
mockRequest
,mockResponse
andmockParams
withrequest
,response
andparams
. - Remove references to
renderArgs
and use theview
andmodel
properties for view rendering, orresponse.text
for all others. - Replace references to
redirectArgs
withresponse.redirectedUrl
. The latter takes into account the URL mappings as is a string URL rather than a map ofredirect()
arguments. - The
mockCommandObject()
method is no longer needed as Grails automatically detects whether an action requires a command object or not.
- コアアーテファクト(コントローラ、タグリブ、ドメインクラス等)のテストの場合は、
extends *UnitTestCase
を削除して、@TestFor
アノテーションをクラスに追加します。コアアーティファクト以外やアーティファクト以外の場合は、@TestMixin(GrailsUnitTestMixin)
アノテーションを追加します。 - モックするドメインクラスで、
mockDomain()
の代わりに、new MyDomain().save()
を使用するために、@Mock
アノテーションでドメインクラスを指定します。 mockRequest
、mockResponse
、mockParams
への参照をrequest
、response
、params
に変更します。renderArgs
を参照している部分を削除して、view
とmodel
プロパティをビューレンダリング用に、また他はresponse.text
を使用するようにします。redirectArgs
は、response.redirectedUrl
に変更します。後者はURLマッピングの内容を、redirect()
のマップのでは無く、文字列のURLで返します。mockCommandObject()
メソッドは、アクションが必要であれば自動的にコマンドオブジェクトを認識するため必要無くなりました。
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.echo
in your scripts to communicate messages to the user, we recommend switching to an alternative mechanism.ant.echo
からのメッセージは表示されなくなります。それに変わる方法に変更することをお勧めします。event "StatusUpdate", ["Some message"] event "StatusFinal", ["Some message"] event "StatusError", ["Some message"]
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()
.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キャッシュ場所が変更 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型のドメインプロパティ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.
基盤となるAPIの更新 Updated Underlying APIs
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.HttpServletRequest
インターフェイスは新しい物を多く含んでいます。この逆もあり得るので、Servlet 2.5のインターフェイスで実装され、Servlet 3.0に存在しない機能を持っているプラグインは動作しません。もちろんこの事はSpringなど他のライブラリにも同じ事が言えます。注意しましょう。release-pluginコマンド除去 Removal of release-plugin
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
grails.web.JsonBuilder
, grails.web.OpenRicoBuilder
grails.web.JsonBuilder
, grails.web.OpenRicoBuilder
Grails 1.2.x からのアップグレード Upgrading from Grails 1.2.x
プラグイン・リポジトリ Plugin Repositories
Grails 1.1.x からのアップグレード Upgrading from Grails 1.1.x
翻訳チームの判断により、Grails 1.1.xからの更新は翻訳を行いません。ご了承ください。
プラグインのパス Plugin paths
pluginContextPath
variable was used to establish paths to plugin resources. For example:pluginContextPath
が、以下のように使用されていました:<g:resource dir="${pluginContextPath}/images" file="foo.jpg" />
<g:resource dir="images" file="foo.jpg" />
<g:resource contextPath="" dir="images" file="foo.jpg" />
タグとボディの戻り値 Tag and Body return values
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:java.lang.String
インスタンスを返さず、その代わりにStreamCharBuffer
インスタンスを返します。StreamCharBuffer
クラスは、String
と同じメソッドを実装していますが、このようなコードの場合は破綻します:def foo = body() if (foo instanceof String) { // do something }
java.lang.CharSequence
interface, which both String
and StreamCharBuffer
implement:String
とStreamCharBuffer
の両方が実装しているjava.lang.CharSequence
インタフェースを使用します:def foo = body() if (foo instanceof CharSequence) { // do something }
新しいJSONBuilder 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:
grails.json.legacy.builder=true
フラッシュでのバリデーション 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 fromgrails.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
:
grails.views.enable.jsessionid=true
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
:
grails.project.plugins.dir="./plugins"
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:
Ant.property(environment:"env") 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(
"grails-app/conf/my-config.xml")
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:
"/book"(controller:"book",parseRequest:true)
Alternatively, you can use the new resource
argument, which enables parsing by default:
"/book"(resource:"book")
4 設定
4.1 基本設定
grails-app/conf/BuildConfig.groovy
grails-app/conf/Config.groovy
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.
BuildConfig.groovy
はcompile
やdoc
等のようなGrailsコマンドを実行するときに使われる設定です。
2つめのConfig.groovy
はアプリケーションを実行するときに使われる設定です。
つまり、Config.groovy
はアプリケーションにパッケージされますが、BuildConfig.groovy
はされません。
違いがよく分からなくても心配する必要はありません。
どの設定をどのファイルに書くべきかはこのガイドで示していきます。foo.bar.hello = "world"
foo.bar.hello = "world" foo.bar.good = "bye"
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" } }
foo { bar.hello = "world" bar.good = "bye" }
// Won't work! foo.bar { hello = "world" good = "bye" }
BuildConfig.groovy
and Config.groovy
you can access several implicit variables from configuration values:
BuildConfig.groovy
とConfig.groovy
内では、設定値からいくつかの暗黙の変数にアクセスできます:Variable | Description |
---|---|
userHome | Location of the home directory for the account that is running the Grails application. |
grailsHome | Location of the directory where you installed Grails. If the GRAILS_HOME environment variable is set, it is used. |
appName | The application name as it appears in application.properties. |
appVersion | The application version as it appears in application.properties. |
変数 | 説明 |
---|---|
userHome | Grailsアプリケーションを実行しているアカウントのホームディレクトリの場所です。 |
grailsHome | Grailsがインストールされているディレクトリの場所です。環境変数GRAILS_HOME が設定されているときはその値が格納されます。 |
appName | application.properties内に表記しているアプリケーション名です。 |
appVersion | application.properties内に表記しているアプリケーションバージョンです。 |
my.tmp.dir = "${userHome}/.grails/tmp"
BuildConfig.groovy
has
BuildConfig.groovy
は以下の変数を持っています。Variable | Description |
---|---|
grailsVersion | The version of Grails used to build the project. |
grailsSettings | An object containing various build related settings, such as baseDir . It's of type BuildSettings . |
変数 | 説明 |
---|---|
grailsVersion | プロジェクトをビルドするために使われたGrailsのバージョンです。 |
grailsSettings | baseDir のような、ビルドに関連する様々な設定を格納したオブジェクトです。型はBuildSettings です。 |
Config.groovy
has
Config.groovy
は以下の変数を持っています。Variable | Description |
---|---|
grailsApplication | The GrailsApplication instance. |
変数 | 説明 |
---|---|
grailsApplication | GrailsApplication のインスタンスです。 |
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 … }
Config.groovy
, use the grailsApplication
object, which is available as a variable in controllers and tag libraries:
Config.groovy
に定義されたものを読みたい場合は、grailsApplication
オブジェクトを使って、コントローラやタグライブラリから変数として取得できます:class MyController { def hello() { def recipient = grailsApplication.config.foo.bar.hellorender "Hello ${recipient}" } }
class MyService { def grailsApplicationString greeting() { def recipient = grailsApplication.config.foo.bar.hello return "Hello ${recipient}" } }
4.1.1 組込オプション
Build settings
ビルド設定
BuildConfig.groovy
:
BuildConfig.groovy
内で次のように設定します:grails.project.source.level = "1.5" grails.project.target.level = "1.5"
grails.servlet.version
setting appropriately:
grails.servlet.version
を適切に設定します:grails.servlet.version = "3.0"
Runtime settings
ランタイム設定
Config.groovy
, there are quite a few more core settings:
Config.groovy
には非常に多くのコアな設定があります: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
andgrails.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 therun-app
command. If thegrails.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.excludes
とgrails.reload.includes
- このディレクティブの設定は、プロジェクト固有のソースファイルに対するリロードの挙動を決めます。それぞれのディレクティブは文字列のリストを取ります。この文字列はrun-app
コマンドを使って開発時にアプリケーションを動作させる際、リロード対象から除外または含めるべきプロジェクトのソースファイルのクラス名です。grails.reload.includes
ディレクティブが設定されている場合、リストにあるクラスだけがリロードされます。
War generation
Warの生成
grails.project.war.file
- Sets the name and location of the WAR file generated by the war commandgrails.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ファイルをビルドする前に、その他の作業を行うことをアプリケーションに許可します。
4.1.2 ロギング
The Basics
基本
log4j
setting to the file grails-app/conf/Config.groovy
.
log4j
設定をgrails-app/conf/Config.groovy
ファイルに追加するだけです。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' // GSPwarn 'org.apache.catalina' }
Logging levels
ログレベル
- off
- fatal
- error
- warn
- info
- debug
- trace
- all
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」を除いた上記のレベルには、それぞれに対応する同名のログメソッドがあります。warn 'org.example.domain'
Loggers
ロガー
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つの別々のクラスが同じ名前のロガーを使う場合、そのロガーは実際に同一のインスタンスとなります。- use the
log
instance injected into artifacts such as domain classes, controllers and services; - use the Commons Logging API directly.
- ドメインクラスやコントローラ、サービスのようなアーティファクトに注入される
log
インスタンスを使う - Commons Logging APIを直接使う
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.exampleclass MyService { … }
package org.otherimport org.apache.commons.logging.LogFactory
class MyClass { private static final log = LogFactory.getLog(this) … }
getLog()
method, such as "myLogger", but this is less common because the logging system treats names with dots ('.') in a special way.
getLog()
メソッドに渡すこともできます。
しかし、ロギングシステムがドット(.)付きの名前を特別な方法で扱うため、これはあまり一般的ではありません。Configuring loggers
log4j = { error 'org.codehaus.groovy.grails.web.servlet' }
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.GrailsDispatcherServlet
クラスとorg.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest
クラスの両方に適用されます。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" }
conf
- For anything undergrails-app/conf
such asBootStrap.groovy
(but excluding filters)filters
- For filterstaglib
- For tag librariesservices
- For service classescontrollers
- For controllersdomain
- For domain entities
conf
-BootStrap.groovy
のようなgrails-app/conf
配下にあるもの (フィルタは除く)filters
- フィルタtaglib
- タグライブラリservices
- サービスクラスcontrollers
- コントローラdomain
- ドメインエンティティ
org.codehaus.groovy.grails.commons
- Core artifact information such as class loading etc.org.codehaus.groovy.grails.web
- Grails web request processingorg.codehaus.groovy.grails.web.mapping
- URL mapping debuggingorg.codehaus.groovy.grails.plugins
- Log plugin activitygrails.spring
- See what Spring beans Grails and plugins are definingorg.springframework
- See what Spring is doingorg.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が何をするのか
The Root Logger
ルートロガー
log4j = { root { info() } … }
log4j = {
appenders {
file name:'file', file:'/var/logs/mylog.log'
}
root {
debug 'stdout', 'file'
}
}
stdout
(コンソール)アペンダと自前のfile
アペンダの2つに対してログ出力します。org.apache.log4j.Logger
instance is passed as an argument to the log4j closure. This lets you work with the logger directly:
org.apache.log4j.Logger
インスタンスが渡されます。
これでロガーを直接操作できます:log4j = { root -> root.level = org.apache.log4j.Level.DEBUG … }
Logger
instance, refer to the Log4j API documentation.
Logger
インスタンスでできることについての詳細は、Log4jのAPIドキュメントを参照してください。Appenders
アペンダ
stdout
という名前のコンソールアペンダが、ルートロガーの設定を通じて全てのロガーに繋がっています。
しかし、それ以外のアペンダはありません。
appenders
ブロックで、さらにアペンダを追加することができます:log4j = { appenders { rollingFile name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log" } }
Name | Class | Description |
---|---|---|
jdbc | JDBCAppender | Logs to a JDBC connection. |
console | ConsoleAppender | Logs to the console. |
file | FileAppender | Logs to a single file. |
rollingFile | RollingFileAppender | Logs to rolling files, for example a new file each day. |
名前 | クラス | 説明 |
---|---|---|
jdbc | JDBCAppender | JDBC接続に記録します。 |
console | ConsoleAppender | コンソールに記録します。 |
file | FileAppender | 単一ファイルに記録します。 |
rollingFile | RollingFileAppender | ローテーションするファイルに記録します。例えば日次で新しいファイルにします。 |
name
, maxFileSize
and file
properties of the RollingFileAppender
instance.
RollingFileAppender
のインスタンスのname
とmaxFileSize
、file
プロパティを設定しています。appender
entry with an instance of the appender you want:
appender
エントリを単純に宣言してください。import org.apache.log4j.*log4j = { appenders { appender new RollingFileAppender( name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log") } }
JMSAppender
, SocketAppender
, SMTPAppender
, and more.
JMSAppender
、SocketAppender
、SMTPAppender
などを設定するために使われます。error myAppender: "grails.app.controllers.BookController"
grails.app.controllers.BookController
のロガーが、ルートロガーによって設定されたアペンダだけでなく、myAppender
にもログメッセージを送るようにします。
1つ以上のアペンダをロガーに追加するには、同じレベルの宣言に追加します:error myAppender: "grails.app.controllers.BookController", myFileAppender: ["grails.app.controllers.BookController", "grails.app.services.BookService"], rollingFile: "grails.app.controllers.BookController"
myFileAppender
) by using a list.
myFileAppender
)に対して、リストを使ってどのように1つ以上のロガーを同時に設定するかについても示しています。error myAppender: "grails.app.controllers.BookController" debug myFileAppender: "grails.app.controllers.BookController" fatal rollingFile: "grails.app.controllers.BookController"
grails.app.controllers.BookController
のために「fatal」レベルのメッセージだけを記録するというのがわかるでしょう。
特定のロガーに対して宣言した最後のレベルが勝つためです。
おそらく行いたいことは、アペンダが書き込むメッセージのレベルを制限することです。log4j = {
appenders {
console name: "stdout", threshold: org.apache.log4j.Level.INFO
}
}
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
カスタムレイアウト
xml
- Create an XML log filehtml
- Creates an HTML log filesimple
- A simple textual logpattern
- A Pattern layout
xml
- XMLログファイルを作成html
- HTMLログファイルを作成simple
- シンプルなテキストログpattern
- パターンレイアウト
layout
setting:
layout
設定を使ってアペンダに独自のパターンを指定できます:log4j = { appenders { console name: "customAppender", layout: pattern(conversionPattern: "%c{2} %m%n") } }
stdout
でも動作します。log4j = { appenders { console name: "stdout", layout: pattern(conversionPattern: "%c{2} %m%n") } }
Environment-specific configuration
環境ごとの設定
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
の完全なロギング設定を記述しなければならないのです。
言い換えると、設定の特定の部分だけ都合良く上書きすることができません。
全部書くか、まったく書かないかのどちらかしかありません。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" } } }
root
definition, but you can put the root
definition inside an environment block.
root
定義 内 では環境ブロックが使用できませんが、代わりに環境ブロック内へroot
定義を配置してください。Full stacktraces
完全なスタックトレース
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"
stacktrace.log
ファイルを作成しなくなるわけではありません。
単にスタックトレースが書かれるべき場所を変更するだけです。
別の方法はstacktrace
アペンダのファイル場所を変更することです:log4j = { appenders { rollingFile name: "stacktrace", maxFileSize: 1024, file: "/var/tmp/logs/myApp-stacktrace.log" } }
stacktrace
アペンダがまったく必要なければ、null
アペンダとして設定します:log4j = { appenders { 'null' name: "stacktrace" } }
StackTrace
ロガーのstdout
アペンダへの接続と、このnull
アペンダの設定を組み合わせることができます。grails.full.stacktrace
VM property to true
:
grails.full.stacktrace
をtrue
に設定すると、スタックトレースフィルタを完全に無効にできます:grails -Dgrails.full.stacktrace=true run-app
Masking Request Parameters From Stacktrace Logs
スタックトレースログからリクエストパラメータをマスクする
grails.exceptionresolver.params.exclude
config property:
grails.exceptionresolver.params.exclude
の設定値にパラメータ名を指定します。grails.exceptionresolver.params.exclude = ['password', 'creditCard']
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
になります。grails.exceptionresolver.logRequestParameters=false
Logger inheritance
ロガーの継承
log4j = {
appenders {
file name:'file', file:'/var/logs/mylog.log'
}
root {
debug 'stdout', 'file'
}
}
stdout
アペンダとfile
アペンダの両方にログが出力されます。
もし特定のロガーに対してのみstdout
にログを出力したい場合はどうすればよいでしょう?このような場合は、ロガーに対してadditivity
を変更してください。false
の場合、親から設定を継承しません。
すべてのロガーのデフォルトはtrue
で親の設定を継承します。
この設定をどのように変更するのでしょうか?
以下に例を示します:log4j = { appenders { … } root { … }info additivity: false stdout: ["grails.app.controllers.BookController", "grails.app.services.BookService"] }
additivity
という名前の引数を追加します。
additivity
を指定するときは、名前付きのアペンダに対してロガーの設定をしなければなりません。
例えば以下の構文では正しく動作 しません :info additivity: false, ["grails.app.controllers.BookController", "grails.app.services.BookService"]
Customizing stack trace printing and filtering
スタックトレースの表示とフィルタリングをカスタマイズする
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
:
org.codehaus.groovy.grails.exceptions.StackTraceFilterer
インタフェースの実装を使用しています。このフィルタリング方法をカスタマイズするには、src/groovy
またはsrc/java
にインタフェースの実装クラスを配置し、そのクラスをConfig.groovy
で登録します:grails.logging.stackTraceFiltererClass = 'com.yourcompany.yourapp.MyStackTraceFilterer'
org.codehaus.groovy.grails.exceptions.StackTracePrinter
interface in a class in src/groovy or src/java and register it in Config.groovy
:
src/groovy
またはsrc/java
にorg.codehaus.groovy.grails.exceptions.StackTracePrinter
インタフェースの実装クラスを配置し、そのクラスをConfig.groovy
で登録します:grails.logging.stackTracePrinterClass = 'com.yourcompany.yourapp.MyStackTracePrinter'
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:
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.MyErrorsViewStackTracePrinterbeans = {
errorsViewStackTracePrinter(MyErrorsViewStackTracePrinter, ref('grailsResourceLocator')) }
Alternative logging libraries
ロギングライブラリの変更
grails.project.dependency.resolution = { inherits("global") { excludes "grails-plugin-logging", "log4j" } … dependencies { runtime "ch.qos.logback:logback-core:0.9.29" … } … }
4.1.3 GORM
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メソッドのドキュメントを参照してください。
grails.gorm.failOnError=true
grails.gorm.failOnError = ['com.companyname.somepackage', 'com.companyname.someotherpackage']
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)
を使用して明示的にフラッシュする必要がなくなり、merge、save、deleteメソッドはセッションをフラッシュするようになります。
4.2 環境
環境ごとの設定
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-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" } } }
environments
block specifies per environment settings for the dbCreate
and url
properties of the DataSource
.environments
ブロックにはDataSource
のdbCreate
やurl
プロパティを環境ごとに指定している様子がわかります。異なる環境のパッケージングと実行
grails [environment] [command name]
dev
, prod
, and test
for development
, production
and test
. For example to create a WAR for the test
environment you wound run:dev
,prod
,test
(development
,production
,test
)といった、あらかじめ定義されている3つの環境が知られています。例えば、test
環境でWARを作成するには、以下のように実行します。grails test war
grails.env
variable to any command:grails.env
変数を渡すことで実現できます。grails -Dgrails.env=UAT run-app
プログラマチック環境検出
import grails.util.Environment...
switch (Environment.current) { case Environment.DEVELOPMENT: configureForDevelopment() break case Environment.PRODUCTION: configureForProduction() break }
環境ごとのブートストラップ
grails-app/conf/BootStrap.groovy
file's support for per-environment execution:grails-app/conf/BootStrap.groovy
ファイルの環境ごとの実行サポートを使います。def init = { ServletContext ctx -> environments { production { ctx.setAttribute("env", "prod") } development { ctx.setAttribute("env", "dev") } } ctx.setAttribute("foo", "bar") }
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:BootStrap
の例では、内部的にgrails.util.Environment
クラスを使用して実行しています。独自の環境ロジックを実行するために、このクラスを以下のように使うこともできます。Environment.executeForCurrentEnvironment { production { // do something in production } development { // do something only in development } }
4.3 データソース
grails.project.dependency.resolution = { inherits("global") log "warn" repositories { grailsPlugins() grailsHome() grailsCentral() mavenCentral() } dependencies { runtime 'mysql:mysql-connector-java:5.1.16' } }
mavenCentral()
repository is included here since that's a reliable location for this library.mavenCentral()
リポジトリが記述されているのは、このライブラリの取得元として信頼できる場所だからです。lib
directory.lib
ディレクトリにJARを置いてください。grails-app/conf/DataSource.groovy
. This file contains the dataSource definition which includes the following settings:grails-app/conf/DataSource.groovy
ファイルで使用する、Grailsにおけるデータソースの定義方法を覚える必要があります。このファイルはデータソースの定義として、以下の項目を含んでいます。driverClassName
- The class name of the JDBC driver
username
- The username used to establish a JDBC connectionpassword
- The password used to establish a JDBC connectionurl
- The JDBC URL of the databasedbCreate
- 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 stdoutformatSql
- Format logged SQLdialect
- 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
- Iftrue
makes the DataSource read-only, which results in the connection pool callingsetReadOnly(true)
on eachConnection
persistenceInterceptor
- The default datasource is automatically wired up to the persistence interceptor, other datasources are not wired up automatically unless this is set totrue
properties
- Extra properties to set on the DataSource bean. See the Commons DBCP BasicDataSource documentation.
driverClassName
- JDBCドライバのクラス名username
- JDBCコネクションの接続に使用するユーザ名password
- JDBCコネクションの接続に使用するパスワードurl
- データベースのJDBC URLdbCreate
- ドメインモデルからデータベースを自動で生成するか。'create-drop'、'create'、'update'、もしくは'validate'の中から1つ指定pooled
- コネクションプールを使うか(デフォルトではtrue)logSql
- 標準出力へのSQLロギングを有効にするかformatSql
- SQLログをフォーマットするかdialect
- データベースの通信に使用されるHibernateの方言を表す文字型かクラス。利用できる方言はorg.hibernate.dialectパッケージを参照readOnly
- true
にした場合は読み取り専用のデータソースとなり、各Connection
でsetReadOnly(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ドキュメント参照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 … }
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 */" } }
dbCreateの詳細
dbCreate
property, which can take these values:dbCreate
プロパティを使い、どのようにテーブルの作成を行うのかコントロールすることができ、以下のような値を取ることができます。- 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
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 データソースと環境
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 データソース
JNDIデータソースの参照
DataSource
instances via Java Naming and Directory Interface (JNDI). Grails supports the definition of JNDI data sources as follows:DataSource
インスタンスを提供しています。Grailsでは次のようにJNDIデータソースの定義をサポートしています。dataSource {
jndiName = "java:comp/env/myDataSource"
}
DataSource
in Grails remains the same.DataSource
を定義する方法は変わらず同じです。開発時におけるJNDIリソースの設定
grails.naming.entries
setting in grails-app/conf/Config.groovy
:grails-app/conf/Config.groovy
内のgrails.naming.entries
の設定を使用することで、JNDIリソースを定義します。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 自動データベースマイグレーション
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:DataSource
定義のdbCreate
プロパティは、Grailsが実行時にGORMのクラスから自動的にデータベーステーブルを生成すべきかを指示する重要なプロパティです。以下のオプションはDataSourceのセクションで説明しています。
create
create-drop
update
validate
- no value
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.dbCreate
はデフォルト値が"create-drop"で設定されていますが、開発中(もしくは本番以前)では、サーバの起動ごとにデータベースが削除、再作成されることが不都合な場合があります。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.update
に切り替えたくなりますが、Hibernateの更新サポートはあまりパッとしません。データの損失につながる可能性のある変更をすることはありませんが、テーブルやカラム名の変更を見つけることができないので、古いテーブルやカラムは残されて新しいものも持つことになります。grails-app/conf/BuildConfig.groovy
:grails-app/conf/BuildConfig.groovy
に宣言することでプラグインとしてインストールすることができます。:grails.project.dependency.resolution = { … plugins { runtime ':database-migration:1.3.1' } }
4.3.4 Transaction-awareデータソースプロキシ
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.dataSource
ビーンはトランザクション対応のプロキシでラップされているため、それらが開始されているのであれば、現在のトランザクションやHibernateセッションで使われているコネクションが得られます。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).dataSource
としてトランザクション対応のプロキシを使っていなかったとしたら、そのdataSource
から取得したコネクションは新規コネクションであり、(READ_COMMITTED
やより上位の適切なトランザクション分離が設定されていると仮定すれば)まだコミットされていない変更はみえないことでしょう。
dataSource
is still available to you if you need access to it; its bean name is dataSourceUnproxied
.dataSource
にアクセスする必要があるなら、dataSourceUnproxied
というビーン名を使って利用できます。class MyService {def dataSourceUnproxied … }
ApplicationContext
:ApplicationContext
から取得できます。def dataSourceUnproxied = ctx.dataSourceUnproxied
4.3.5 データベースコンソール
grails.dbconsole.urlRoot
attribute in Config.groovy and defaults to '/dbconsole'
.grails.dbconsole.urlRoot
属性を使って設定することが可能で、デフォルト値は'/dbconsole'
になっています。grails.dbconsole.enabled
attribute in Config.groovy. For example you could enable the console in production usinggrails.dbconsole.enabled
属性を使って無効にしたり、他のモードで有効にすることができます。例えば、本番環境(production)でコンソールを有効にするには、次のように記述します。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.
本番環境でコンソールを有効にする場合は、信頼されるセキュリティフレームワークを使用して、コンソールへのアクセスを保護するようにしてください。
設定
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.jdbc:h2:mem:devDB
に変更してください。外部データベース(例えば、MySQL,Oracleなど)を設定する場合には、ドロップダウンのリストから設定テンプレートを選択し、DataSource.groovyからurlやユーザ名/パスワードを設定します。
4.3.6 複数データソース
DataSource
and a single database, but you have the option to partition your domain classes into two or more DataSource
s.DataSource
configuration in grails-app/conf/DataSource.groovy
looks something like this:DataSource
はgrails-app/conf/DataSource.groovy
で設定されており、次のようになっています。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" } } }
DataSource
with the Spring bean named dataSource
. To configure extra DataSource
s, 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:dataSource
と命名されたSpringビーンとして、単一のDataSource
を設定しています。複数のDataSource
を設定するには、アンダースコア(_)で区切られたカスタム名を持つ、別のdataSource
ブロックを(トップレベルかenvironmentブロック、または両方へ標準のDataSource
定義と同様に)追加します。例えば、以下の設定では開発環境にMySQLを、本番環境にOracleを2番目のDataSource
として追加しています。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' } } }
ドメインクラスの設定
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' } }
DataSource
s. Use the datasources
property with a list of names to configure more than one, for example:DataSource
を使用することもできます。複数の設定をするためには、datasources
プロパティにデータソース名のリストを設定します。例えば:class ZipCode {String code
static mapping = { datasources(['lookup', 'auditing']) } }
DataSource
and one or more others, use the special name 'DEFAULT'
to indicate the default DataSource
:DataSource
を持ち、デフォルトのDataSource
を使う場合はデフォルトのDataSource
を指す特別な名前として'DEFAULT'
を使うことができます。class ZipCode {String code
static mapping = { datasources(['lookup', 'DEFAULT']) } }
DataSource
s use the special value 'ALL'
:DataSource
を使う場合、特別な値として'ALL'
を使います。class ZipCode {String code
static mapping = { datasource 'ALL' } }
名前空間とGORMメソッド
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 DataSource
s:DataSource
を使用している場合、特定のDataSource
へGORMの呼び出しを行うために、DataSource
名ごとに暗黙で定義された名前空間を使うことが出来ます。例えば、2つのDataSource
が使われているこのクラスを考えます。class ZipCode {String code
static mapping = { datasources(['lookup', 'auditing']) } }
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) … zipCode.auditing.save()
DataSource
to the method call in both the static case and the instance case.DataSource
を追加します。ドメインクラスのHibernateマップ
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.grails-app/conf/hibernate/hibernate.cfg.xml
に登録されます。デフォルトでないデータソースを使う注釈されたクラスを明示するためには、ファイル名の先頭にデータソース名をつけたhibernate.cfg.xml
を作成します。Book
class is in the default datasource, you would register that in grails-app/conf/hibernate/hibernate.cfg.xml
:Book
クラスがデフォルトのデータソースを使う場合、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' 'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'> <hibernate-configuration> <session-factory> <mapping class='org.example.Book'/> </session-factory> </hibernate-configuration>
Library
class is in the "ds2" datasource, you would register that in grails-app/conf/hibernate/ds2_hibernate.cfg.xml
:Library
クラスが"ds2"データソースを使う場合、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' 'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'> <hibernate-configuration> <session-factory> <mapping class='org.example.Library'/> </session-factory> </hibernate-configuration>
サービス
DataSource
and PlatformTransactionManager
. To configure a Service to use a different DataSource
, use the static datasource
property, for example:DataSource
とPlatformTransactionManager
が使用されます。サービスの設定で異なるDataSource
を使用する場合は、staticなdatasource
プロパティを使用します。例えば:class DataService {static datasource = 'lookup'
void someMethod(...) { … } }
DataSource
, so be sure to only make changes for domain classes whose DataSource
is the same as the Service.DataSource
がサービスと同じドメインクラスだけ値を変更できることに注意してください。XAと2相コミット
DataSource
s 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 DataSource
s.DataSource
や2相コミットに対応していませんが、Atomikosプラグインで簡単に行うことができます。DataSource
定義をXA DataSource
として再設定するのには簡単な変更が必要となるため、プラグインのドキュメントを参照してください。4.4 設定の外部化
grails.config.locations
setting in Config.groovy
, for example:Config.groovy
ファイルにgrails.config.locations
の設定を追加し、設定ファイルの位置をGrailsに伝えます。例えば:grails.config.locations = [ "classpath:${appName}-config.properties", "classpath:${appName}-config.groovy", "file:${userHome}/.grails/${appName}-config.properties", "file:${userHome}/.grails/${appName}-config.groovy" ]
USER_HOME
.USER_HOME
内のファイルといった異なる場所から、設定ファイル(Javaのプロパティファイルや ConfigSlurper 設定ファイル)を読み込んでいます。grails.config.locations = [com.my.app.MyConfig]
config
property of the GrailsApplication object and are hence obtainable from there.config
プロパティへ統合され、そこから取得可能です。デフォルトの設定
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.grails.config.defaults.locations
プロパティから読み込んだ設定値は、アプリケーションのConfig.groovy
で定義された任意の値を上書きします。アプリケーションのConfig.groovy
ファイルか、指定した設定ファイル場所のいずれかで値をオーバライドすることで、デフォルト値として値を読み込ませることが出来ます。これについては、grails.config.defaults.locations
プロパティを使用することができます。
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.config.locations
プロパティと同じ値(すなわち、設定スクリプト、プロパティのファイルやクラスへのパス)をサポートしています。しかし、grails.config.defaults.locations
で記述された設定ははじめに読み込まれるため、あとから読み込む設定値で上書きすることができます。プラグインの中にはこのメカニズムを利用して、プラグインが提供するデフォルト値をアプリケーションに含めるかをユーザが選択する形をとっているものがあります。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 バージョニング
バージョン管理の基本
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.0.1
に設定されています。バージョンは、プロジェクトルートにあるアプリケーションのメタデータファイルのapplication.properties
に記述されます。grails set-version 0.2
実行時のバージョン検出
def version = grailsApplication.metadata['app.version']
def grailsVersion = grailsApplication.metadata['app.grails.version']
GrailsUtil
class:GrailsUtil
クラスを使います。import grails.util.GrailsUtil
…
def grailsVersion = GrailsUtil.grailsVersion
4.6 プロジェクト・ドキュメント
プロジェクトドキュメントの作成
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
ディレクトリを作る必要があります。次に、ソースファイル自体を作成する必要があります。すべてのサブセクションに番号が振られているように、各章には独自のgdocファイルをもつべきです。以下のようになります。+ 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
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:src/docs/guide/toc.yml
ファイルを追加します。このファイルはYAML形式で、基本的にはツリー形式でユーザガイドの構造を表しています。例えば、上記のファイル構造は次のように表すことができます。introduction: title: Introduction changes: Change Log gettingStarted: Getting Started configuration: title: Configuration build: title: Build Config controllers: Specifying Controllers
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.title:
に加えて、エンドユーザが目にするセクションのタイトルを記述します。すべてのサブセクションではタイトルの後に独自のラインを持っています。サブセクションを持たないセクションでは、セクション名と同じ行のコロンの後にタイトルを宣言します。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.toc.yml
内部で簡単にセクションの追加や削除、移動ができます。すべてのセクション名(gdocのファイル名)はユニークである必要があります。なぜなら、それらは内部リンクの作成やHTMLのファイル名に使用されるからです。しかし、心配はいりません。ドキュメンテーションエンジンはセクション名が重複していた場合に警告を表示します。参照項目の作成
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
ディレクトリに配置します。例えば、コントローラに新しくrenderPDF
のメソッドを定義したとしましょう。これがControllers
カテゴリに所属する場合、以下のようにgdocのテキストファイルを作成します。:+ src/docs/ref/Controllers/renderPDF.gdoc
出力プロパティの設定
grails-app/conf/Config.groovy
file that customize the output of the documentation such as:grails-app/conf/Config.groovy
内で設定できる様々なプロパティがあります。- 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 - 使用するフッター
- 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
の型)
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.grails.doc.css
の値を記述し、対応するディレクトリにcustom.cssファイルを置くことです。Grailsは自動的にドキュメント内にこのCSSファイルを取り込みます。また、そのディレクトリにcustom-pdf.cssファイルを置くことができます。これは、ドキュメントのpdfバージョンのスタイルを上書きできます。ドキュメントの生成
grails doc
docs/manual/index.html
which can be opened in a browser to view your documentation.docs/manual/index.html
に出力されます。ドキュメントの構文
基本的なフォーマット
monospace
monospace
@monospace@
_italic_
*bold*

!http://grails.org/images/new/grailslogo_topNav.png!
!someFolder/my_diagram.png!
grails.doc.images
setting in Config.groovy like so:grails.doc.images
の設定で指定できます。grails.doc.images = new File("src/docs/images")
リンク生成
[SpringSource|http://www.springsource.com/]
or
"SpringSource":http://www.springsource.com/
guide:
prefix with the name of the section you want to link to:guide:
をつけることで実現できます。[Intro|guide:introduction]
[controllers|renderPDF]
api:
prefix. For example:api:
プレフィックスを使うことで外部APIへリンクできます。例えば:[String|api:java.lang.String]
grails-app/conf/Config.groovy
. For example:grails-app/conf/Config.groovy
に設定を追加することで、エンジンに追加のAPIを加えることができます。例えば:grails.doc.api.org.hibernate=
"http://docs.jboss.org/hibernate/stable/core/javadocs"
org.hibernate
package to link to the Hibernate website's API docs.org.hibernate
パッケージ内のクラスを、HibernateのAPIドキュメントへリンクするように設定しています。リストと見出し
h3.<space>Heading3 h4.<space>Heading4
* item 1 ** subitem 1 ** subitem 2 * item 2
# item 1
table
macro:table
マクロを使って作成できます。Name | Number |
---|---|
Albert | 46 |
Wilma | 1348 |
James | 12 |
{table}
*Name* | *Number*
Albert | 46
Wilma | 1348
James | 12
{table}
コードとノート
code
macro:code
マクロでコードブロックを定義できます。class Book {
String title
}
{code}
class Book {
String title
}
{code}
<hello>world</hello>
{code:xml} <hello>world</hello> {code}
Note:
This is a note!
{note} This is a note! {note}
Warning:
This is a warning!
{warning} This is a warning! {warning}
4.7 依存性解決
grails.project.dependency.resolver
setting in grails-app/conf/BuildConfig.groovy
. The default setting is shown below:grails-app/conf/BuildConfig.groovy
ファイル内のgrails.project.dependency.resolver
を設定することで指定出来ます。デフォルト設定は次のとおりです:grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution
property inside the grails-app/conf/BuildConfig.groovy
file that configures how dependencies are resolved:grails-app/conf/BuildConfig.groovyの
ファイル内の、grails.project.dependency.resolution
プロパティを次のように指定することで、依存関係を解決する方法が設定できます:grails.project.dependency.resolution = { // config here }
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" } }
4.7.1 設定と依存
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ファイルのデプロイ時には不必要な依存関係
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:dependencies
ブロックの内部で上記のメソッドを呼び出すことにより、依存関係を指定することができます。たとえば、アプリケーションがruntime
時にMySQLドライバを必要とする場合は、次のように指定することができます:runtime 'com.mysql:mysql-connector-java:5.1.16'
group:name:version
. グループ:名前:バージョン
というString構文を使用しています。
<groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>
runtime group: 'com.mysql', name: 'mysql-connector-java', version: '5.1.16'
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 dependencyversion
- 依存関係のバージョン
extension
(Aether only) - The file extension of the dependencyextension
(Aetherのみ) - 依存関係のファイル拡張子
classifier
- The dependency classifierclassifier
- 依存関係の分類
branch
(Ivy only) - The branch of the dependencybranch
(Ivyのみ) - 依存関係のブランチ
transitive
(Ivy only) - Whether the dependency has transitive dependenciestransitive
(Ivyのみ) - 推移的依存関係の有無
runtime 'com.mysql:mysql-connector-java:5.1.16', 'net.sf.ehcache:ehcache:1.6.1'// Or
runtime( [group:'com.mysql', name:'mysql-connector-java', version:'5.1.16'], [group:'net.sf.ehcache', name:'ehcache', version:'1.6.1'] )
推移的依存関係解決の無効化
runtime('com.mysql:mysql-connector-java:5.1.16', '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).
推移的依存関係解決の無効化は、Ivy依存関係マネージャとだけ連携して動作します。Aetherは推移的解決をサポートしておらず、明示的に除外する必要があります(下記参照)。
特定の推移的依存関係の除外
excludes
option comes in:excludes
オプションを使用します:runtime('com.mysql:mysql-connector-java:5.1.16', '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' ])
exclude
as well, but that can only accept a single string or Map:exclude
オプションを利用する場合も同様ですが、こちらは単一の文字列またはMapのみを許容します:runtime('com.mysql:mysql-connector-java:5.1.16',
'net.sf.ehcache:ehcache:1.6.1') {
exclude "xml-apis"
}
Ivyモジュール構成の使用
dependencyConfiguration
method to specify the configuration to use.dependencyConfiguration
メソッドを用いて使用する構成を指定できます。provided("my.org:web-service:1.0") { dependencyConfiguration "api" }
"default"
will be used (which is also the correct value for dependencies coming from Maven style repositories)."default"
設定が使用されます。(これは、Mavenスタイルのリポジトリから来る依存関係に対しても正しい値です)JARファイルの場所
user.home/.grails/ivy-cache
or user.home/.m2/repository
when using Aether. You can change this either via the settings.groovy
file:user.home/.grails/ivy-cache
もしくはuser.home/.m2/repository
(Aether使用時)に配置されます。settings.groovy
ファイルによって、この場所を変更できます:grails.dependency.cache.dir = "${userHome}/.my-dependency-cache"
grails.project.dependency.resolution = {
…
cacheDir "target/ivy-cache"
…
}
settings.groovy
option applies to all projects, so it's the preferred approach.settings.groovy
オプションを使用すると、すべてのプロジェクトに適用されるため、こちらがおすすめの方法です。
4.7.2 依存管理リポジトリ
リモートリポジトリ
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:grailsHome()
リポジトリが存在します。公開リポジトリを使用するには、repositories
ブロック内で以下を指定します:repositories { mavenCentral() }
repositories {
mavenRepo "http://repository.codehaus.org"
}
repositories { mavenRepo name: "Codehaus", root: "http://repository.codehaus.org" }
プラグインから継承したリポジトリの制御
repositories {
inherit false
}
オフラインモード
offline
flag to execute Grails commands and Grails will not connect to any remote repositories:offline
フラグを付加してGrailsコマンドを実行すれば、Grailsはリモートリポジトリに接続しません:grails --offline run-app
Note that this command will fail if you do not have the necessary dependencies in your local Ivy cache
ローカルIvyキャッシュ内に必要な依存関係が存在しない場合、このコマンドは失敗することに注意してください。
grails.offline.mode
to true
in ~/.grails/settings.groovy
or in your project's BuildConfig.groovy
file:~/.grails/settings.groovy
ファイルか、プロジェクトのBuildConfig.groovy
ファイルのgrails.offline.mode
をtrue
にすることでにオフラインモードを設定することができます:grails.offline.mode=true
ローカルリゾルバ
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.
AetherはflatDir
リゾルバを含め、いかなるカスタムファイルシステムリゾルバもサポートしていません。上記の機能は、Ivy依存関係マネージャを使用している場合にのみ動作します。
~/.m2/repository
) as a repository:~/.m2/repository
)をリポジトリとして指定する場合は以下のようにします:repositories { mavenLocal() }
カスタムリゾルバ
/* * 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
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"
sshResolver.setCheckmodified(true)
resolver sshResolver }
grails -classpath /path/to/jsch compile|run-app|etc.
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...
コマンドのエイリアスを作成するのが良いでしょう。認証
credentials
block:credentials
ブロックを使用してこれを設定することができます:credentials { realm = ".." host = "localhost" username = "myuser" password = "mypass" }
USER_HOME/.grails/settings.groovy
file using the grails.project.ivy.authentication
setting:grails.project.ivy.authentication
を使用してUSER_HOME/.grails/settings.groovy
ファイル内に記述することができます:grails.project.ivy.authentication = { credentials { realm = ".." host = "localhost" username = "myuser" password = "mypass" } }
4.7.3 依存解決デバッグ
log
method:log
メソッドを使用して内部システムからより詳細なデバッグ情報を得ることができます:// log level of the Aether or Ivy resolver, either 'error', 'warn',
// 'info', 'debug' or 'verbose'
log "warn"
grails.project.dependency.resolution = { … log "warn" checksums false … }
4.7.4 依存の受け継ぎ
inherits "global"
BuildConfig.groovy
file. To exclude specific inherited dependencies you use the excludes
method:BuildConfig.groovy
ファイル内に記載します。特定の依存関係を除外するには、excludes
メソッドを使用します:inherits("global") { excludes "oscache", "ehcache" }
4.7.5 基本依存管理の提供
defaultDependenciesProvided
method and passing true
as an argument:defaultDependenciesProvided
メソッドにtrue
を引数として渡して呼び出すことで実行されます: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 beforeinherits
, otherwise the Grails dependencies will be included in the war.
defaultDependenciesProvided
は、inherits
より前に記述されている必要があり、そうしなければGrailsの依存関係はWARファイルに含まれます。
4.7.6 スナップショットと他の変化する依存関係
変化する依存関係の設定
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".グループ
、名前
、バージョン
の組み合わせが参照するjar(もしくはプラグイン)は変化することはない、ということです。これによりGrailsの依存関係管理システムは、ソースリポジトリから毎回ダウンロードすることを回避するために、依存関係をキャッシュできます。時に、この仕様には不都合が生じます。例えば、多くの開発者は慣習的にスナップショット(つまり、バージョン番号が”-SNAPSHOT”で終わる依存関係)を使っています。このスナップショットは同一のバージョン番号を保持しつつ、変更される可能性があります。このことは”変化する依存関係”と呼ばれています。Be sure to read the next section on “Dependency Resolution Caching” in addition to this one as it affects changing dependencies.
変化する依存関係に作用する、依存関係解決キャッシングについて、次のセクションを必ずお読みください。
-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):暗黙的に
バージョン番号が-SNAPSHOT
で終わるすべての依存関係(jarファイルもしくはプラグイン)を、変化する依存関係として扱います。また、明示的に依存DSLクエリー言語に変更フラグを設定することでも、変化する依存関係として扱う事ができます。(このDSLクエリー言語はIvyにのみ必要です。Aetherは'changing'フラグをサポートしておらず、-SNAPSHOTで終わる場合は変化する依存関係として扱います)runtime ('org.my:lib:1.2.3') {
changing = true
}
Aether and SNAPSHOT dependencies
AetherとSNAPSHOTの依存関係
updatePolicy
for the repository where the snapshot was resolved from, for example:
updatePolicy
を設定します。
例えば以下のようにします:repositories {
mavenCentral {
updatePolicy "interval:1"
}
}
updatePolicy
like the above will seriously impact performance of dependency resolution. The possibly configuration values for updatePolicy
are as follows:
updatePolicy
のように、この設定は依存関係解決のパフォーマンスに影響を与えることに注意してください。
updatePolicy
に設定が可能な値は以下のとおりです:never
- Never check for new snapshotsalways
- Always check for new snapshotsdaily
- 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回新しいスナップショットをチェックする
Ivyと変化する依存関係
grails.project.dependency.resolution = { repositories { mavenLocal() mavenRepo "http://my.org/repo" } dependencies { compile "myorg:mylib:1.0-SNAPSHOT" }
- Mavenのローカルリポジトリが検索されますが、依存関係は見つかりません。
- Mavenのネットワークリポジトリが検索され、依存関係をキャッシュへダウンロードして使用します。
BuildConfig.groovy
file. BuildConfig.groovy
のファイルに定義されている順にチェックされることに注意してください。- Mavenのローカルリポジトリが検索されますが、依存関係は見つかりません。
- Mavenのネットワークリポジトリが検索され依存関係が見つかりますが、キャッシュ内のバージョンと同じ最終更新日時のため更新(すなわちダウンロード)はされません。
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のローカルリポジトリが検索されますが、依存関係は見つかりません。
- Mavenのネットワークリポジトリが検索され、キャッシュ内のバージョンよりも新しい依存関係が見つかり、更新(つまり、キャッシュにダウンロード)されます。
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:mylib
ライブラリのローカル上での変更をテストしたい場合を考えてみます。これを行うには、ライブラリをローカル上でビルドし、Mavenのローカルキャッシュにインストールします(方法は特に重要ではありません)。この状況で、依存関係の解決を実行した場合、以下のようになります。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のローカルリポジトリが検索され、キャッシュ内バージョンと同じ”年齢”の依存関係が見つかりますが、更新(すなわちダウンロード)はされません。
- すでに依存関係を発見したため、Mavenのネットワークリポジトリは検索されません。
しません
。mylib 1.0-SNAPSHOT
in the remote repository), you can either:mylib 1.0-SNAPSHOT
をビルドするために)、次のいずれかを実行できます。- Mavenのローカルリポジトリからバージョンを削除する
BuildConfig.groovy
fileBuildConfig.groovy
ファイル内のリポジトリの順序を変更する
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 ofgroup
,name
andversion
). If you want this behavior consider switching to Aether as the dependency manager.
この変化する依存関係の挙動は、Grailsの依存関係管理システムの基礎となっているApache Ivyの変更不可能な特性です。現在のところIvyは、すべてのリポジトリを検索し、同じ依存関係(すなわち等しいグループ
、名前
、バージョン
の組み合わせ)の中から(修正日付の面で)より新しいバージョンのものを探すことはできません。
4.7.7 依存管理レポート
grails dependency-report
target/dependency-report
directory. You can specify which configuration (scope) you want a report for by passing an argument containing the configuration name:target/dependency-report
ディレクトリにレポートが生成されます。設定名を引数に渡すことで、レポートを作成したい設定(スコープ)を指定することもできます:grails dependency-report runtime
dependency-report
command will also output to the console a graph of the dependencies of an application. Example output it shown below:dependency-report
コマンドはアプリケーションの依存関係のグラフをコンソールへ出力します。出力例を以下に示します: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依存
プラグインJARの依存関係を指定する
export
property of the dependency:エクスポートしたくない
依存関係を定義するには、export
プロパティを使用します:
compile('org.spockframework:spock-core:0.5-groovy-1.8') {
export = false
}
compile group: 'org.spockframework', name: 'spock-core',
version: '0.5-groovy-1.8', export: false
You can useexported = false
instead ofexport = false
, but we recommend the latter because it's consistent with the Map argument.
export=false
の代わりにexported=false
を使用することができますが、Mapの引数と一致しているため前者を推奨します。
独自アプリケーションでプラグインのJAR依存関係をオーバーライドする
plugins { compile(":hibernate:$grailsVersion") { excludes "javassist" } }dependencies { runtime "javassist:javassist:3.4.GA" }
excludes
method, effectively excluding the javassist library as a dependency.excludes
メソッドを使用して除外する依存関係を指定することで、Javassistライブラリを依存関係から除外します。
4.7.9 Maven統合
pom.xml
file.pom.xml
ファイルで依存関係の解決が行なわれると判断し、Grailsでの依存関係解決機能は無効化されますpom.xml
file instead.pom.xml
ファイルから依存関係をロードするように教えることができますBuildConfig.groovy
:BuildConfig.groovy
に以下の行を追加するだけで簡単にできます:grails.project.dependency.resolution = {
pom true
..
}
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リポジトリへのデプロイ
mvn install
and mvn deploy
.mvn install
およびmvn deploy
を使用できます。
- maven-install - MavenのローカルキャッシュにGrailsプロジェクトやプラグインをインストールします。
- maven-deploy - MavenのリモートリポジトリにGrailsプロジェクトやプラグインをデプロイします。
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.pom.xml
を生成します。ただし、pom.xml
がすでにプロジェクトルートに存在する場合には、プロジェクトルート上のpom.xml
ファイルが使用されます。maven-installコマンド
maven-install
command will install the Grails project or plugin artifact into your local Maven cache:maven-install
コマンドは、MavenのローカルキャッシュにGrailsプロジェクトやプラグインをインストールします:grails maven-install
maven-deployコマンド
maven-deploy
command will deploy a Grails project or plugin into a remote Maven repository:maven-deploy
コマンドは、MavenのリモートリポジトリにGrailsプロジェクトやプラグインをデプロイします:grails maven-deploy
<distributionManagement>
configuration within a pom.xml
or that you specify the id
of the remote repository to deploy to:pom.xml
ファイル内に必要な<distributionManagement>
の設定がされているか、もしくはデプロイするリモートリポジトリのid
を指定すること前提としています:grails maven-deploy --repository=myRepo
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:repository
引数は、リポジトリの'id'を指定します。この指定した'id'に対するリポジトリの詳細を、grails-app/conf/BuildConfig.groovy
ファイルもしくは$USER_HOME/.grails/settings.groovy
ファイル内で設定します:grails.project.dependency.distribution = { localRepository = "/path/to/my/local" remoteRepository(id: "myRepo", url: "http://myserver/path/to/repo") }
<remoteRepository id="myRepo" url="scp://localhost/www/repository"> <authentication username="..." privateKey="${user.home}/.ssh/id_dsa"/> </remoteRepository>
remoteRepository(id: "myRepo", url: "scp://localhost/www/repository") { authentication username: "...", privateKey: "${userHome}/.ssh/id_dsa" }
grails maven-deploy --repository=myRepo --protocol=webdav
- http
- scp
- scpexe
- ftp
- webdav
グループ、アーティファクト、バージョン
プロジェクト
pom.xml
file. To change the version you can run the set-version
command:pom.xml
ファイル生成時にGrailによって提供されるGrailsアプリケーションの名前とバージョンを使用します。バージョンを変更するには、set-version
コマンドを実行します:grails set-version 0.2
groupId
will be the same as the project name, unless you specify a different one in Config.groovy:groupId
は、Config.groovyに別の名前を指定しない限り、プロジェクト名と同じになります:grails.project.groupId="com.mycompany"
プラグイン
groupId
and version
are taken from the following properties in the GrailsPlugin.groovy
descriptor:groupId
とversion
は、GrailsPlugin.groovy
内の以下のプロパティから取得されます:
String groupId = 'myOrg' String version = '0.1'
FeedsGrailsPlugin
the artifactId
will be "feeds". If your plugin does not specify a groupId
then this defaults to "org.grails.plugins".FeedsGrailsPlugin
というプラグインの場合、artifactId
は "feeds"になります。プラグインがgroupId
を指定していない場合、デフォルト設定の"org.grails.plugins"となります。
4.7.11 プラグイン依存管理
grails.project.dependency.resolution = { … repositories { … }plugins { runtime ':hibernate:1.2.1' }
dependencies { … } … }
org.grails.plugins
is used. org.grails.plugins
が使用されます。Latest Integrationラベル
Only the Ivy dependency manager supports the "latest.integration" version. For Aether you can achieve a similar effect with version ranges.
Ivy依存関係マネージャは"latest.integration"バージョンをサポートしています。Aetherの場合は、バージョンの範囲指定で同様の効果を得ることができます。
plugins { runtime ':hibernate:latest.integration' }
Integrationラベル vs. 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".
"latest.release"ラベルはMavenの互換リポジトリでのみ動作します。通常のSVNベースのGrailsリポジトリの場合は、"latest.integration"を使用する必要があります。
plugins { runtime 'mycompany:hibernate:latest.integration' }
プラグインの除外
plugins {
runtime(':weceem:0.8') {
excludes "searchable"
}
}
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:excludes
メソッドを使用することで、Grailsにsearchableプラグインを推移的にインストール_しない_ことを教えることができます。あわせて、プラグインの代替バージョンを指定することもできます:plugins {
runtime(':weceem:0.8') {
excludes "searchable" // excludes most recent version
}
runtime ':searchable:0.5.4' // specifies a fixed searchable version
}
plugins {
runtime(':weceem:0.8') {
transitive = false
}
runtime ':searchable:0.5.4' // specifies a fixed searchable version
}
4.7.12 依存管理のキャッシュ
grails clean
)- プロジェクトがクリーンな場合(すなわち、チェックアウト直後または
grails clean
の実行後)
BuildConfig.groovy
file has changed since the last command was run- 最後にコマンドが実行された後に、
BuildConfig.groovy
ファイルが変更された場合
--refresh-dependencies
command line switch is provided to the command (any command)--refresh-dependencies
引数が、何らかのコマンドに与えられる場合
refresh-dependencies
command is the command being executedrefresh-dependencies
コマンドが実行された場合
BuildConfig.groovy
) Grails will do the right thing and resolve your new dependencies.BuildConfig.groovy
を変更するたびに)Grailsは正しく新たに依存関係解決を実行します。latest.integration
).
{info}
{info}
変化する依存関係 は、バージョン番号が変更されずに、内容が変化するもの(スナップショットなど)です。 動的な依存関係 は多くの可能なオプションのいずれかとして定義されるものです。(バージョンが範囲指定されている、またはlatest.integration
のように抽象的なバージョン番号を持つ依存関係など)
{info}
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
の依存関係を宣言した場合、サーバー上で使用可能な最新のものを自動的に取得できない可能性があります。- プロジェクトのクリーンアップ
refresh-dependencies
commandrefresh-dependencies
コマンドの実行
--refresh-dependencies
switch; or任意のコマンド
に--refresh-dependencies
を付与して実行
BuildConfig.groovy
BuildConfig.groovy
を変更
--refresh-dependencies
switch to the command you use to build your projects.--refresh-dependencies
を追加しておくと有効でしょう。
5 コマンドライン
grails
command. When you type:grails
コマンドを使用し、Gantとは少し違った実行方法になります。grails [command name]
USER_HOME/.grails/scripts
PROJECT_HOME/scripts
PROJECT_HOME/plugins/*/scripts
GRAILS_HOME/scripts
grails run-app
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
grails help
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左メニューにある個別のコマンドラインリファレンス情報も参照して下さい。
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:run-app
をする際にヒープサイズにより大きな値を設定したいといった場合です。
Grailsコマンドは一般的なJAVA_OPTS
の環境変数内で提供されているJVMオプションを使用しますが、Grails固有の環境変数を指定することもできます:export GRAILS_OPTS="-Xmx1G -Xms256m -XX:MaxPermSize=256m"
grails run-app
非インタラクティブモード
--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.--non-interactive
を渡します。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 フォークモード
フォーク実行
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.run-app
、run-war
、test-app
、console
コマンドはフォークされたJVM上で実行されます。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 ]
フォークされたテスト実行
grails test-app
test-app
from interactive mode will result in faster test execution times:test-app
の実行では、テスト実行時間が速くなります:$ grails $ grails> test-app
grails.project.fork.test
setting to false
:grails.project.fork.test
をfalse
にセットすることで、フォーク実行を無効にすることもできます。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
フォークされた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アプリケーションを並列デプロイできる
grails.project.fork.run
property to true
:grails.project.fork.run
プロパティをtrue
にセットします:grails.project.fork.run=true
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
grails.project.fork.run= [maxMemory:1024, minMemory:64, debug:false, maxPerm:256, jvmArgs: '..arbitrary JVM arguments..']
フォークモードでの追加WARファイルの自動デプロイ
src/autodeploy
directory (if it doesn't exist you can create it).src/autodeploy
ディレクトリに置くことです(もしディレクトリが存在していなければ、作成してください)。BuildConfig.groovy
:BuildConfig.groovy
で別のパスを指定してautodeploy
ディレクトリの位置をカスタマイズできます:grails.project.autodeploy.dir="/path/to/my/war/files"
フォークされたTomcatインスタンスのカスタマイズ
org.grails.plugins.tomcat.ForkedTomcatCustomizer
which provides a method with the following signature:org.grails.plugins.tomcat.ForkedTomcatCustomizer
という名前のクラスを実装します。
このクラスは以下のシグネチャのメソッドを提供します:void customize(Tomcat tomcat) { // your code here }
5.3 Gantスクリプトの作成
grails create-script compile-sources
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:scripts/CompileSources.groovy
というスクリプトが作成されます。Gantスクリプト自身は通常のGroovyスクリプトと似ていますが、ターゲットという概念とそれぞれのターゲットの依存関係をサポートしています。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") }
ant
variable (an instance of groovy.util.AntBuilder
) that allows access to the Apache Ant API.
In previous versions of Grails (1.0.3 and below), the variable was前バージョンのGrails(1.0.3以前)では、変数名はAntのように大文字始まりでした。Ant
, i.e. with a capital first letter.
depends
method demonstrated in the default
target above.depends
メソッドを使って他のターゲットに 依存させることができます。デフォルトターゲット The default target
setDefaultTarget()
method:setDefaultTarget()
メソッドを使用することもできます。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") }
setDefaultTarget("clean-compile")
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")の後であればどこにでも書くことができます。5.4 Grailsスクリプトの再利用
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
includeTargets
property. Simply "append" a file or class to it using the left-shift operator:includeTargets
プロパティにより実現されます。単純に左シフト演算子でファイル又は使用するクラスを追加します:includeTargets << new File("/path/to/my/script.groovy") includeTargets << gant.tools.Ivy
Core Grailsターゲット Core Grails targets
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).includeTargets
では、ファイルベース構文、クラスベース構文のどちらも使用しません。代わりに、Grailsコマンドランチャが提供しているgrailsScript()
という特別なメソッドを使用します(このメソッドはGrails専用であり、通常のGantでは利用できません)。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:grailsScript()
メソッドの構文は、単に含めたいGrailsスクリプトの名称を渡すだけです。以下に再利用できるGrailsスクリプトの一覧を示します:
Script | Description |
---|---|
_GrailsSettings | You 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. |
_GrailsEvents | Include this to fire events. Adds an event(String eventName, List args) method. Again, included by almost all other Grails scripts. |
_GrailsClasspath | Configures 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. |
_GrailsProxy | If you don't have direct access to the internet and use a proxy, include this script to configure access through your proxy. |
_GrailsArgParsing | Provides 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. |
_GrailsTest | Contains all the shared test code. Useful if you want to add any extra tests. |
_GrailsRun | Provides all you need to run the application in the configured servlet container, either normally (runApp /runAppHttps ) or from a WAR file (runWar /runWarHttps ). |
スクリプト | 説明 |
---|---|
_GrailsSettings | Grailsの設定などを読み込むスクリプト。このスクリプトは他のスクリプト(_GrailsProxyなど)で自動的にインクルードされているので、通常は明示的にインクルードする必要はありません。 |
_GrailsEvents | イベントトリガーを実装するためのメソッド(event(String eventName, List args) )を使用するには、これをインクルードする必要があります。このスクリプトもほぼ全てのGrailsスクリプトでインクルードされています。 |
_GrailsClasspath | コンパイル、テスト、およびランタイムのクラスパスを設定します。このスクリプトもほぼ全ての Grailsスクリプトでインクルードされています。 |
_GrailsProxy | インターネットにアクセスする場合は、プロキシの解決をするためにこのスクリプトをインクルードして下さい。 |
_GrailsArgParsing | parseArguments ターゲットはその名の通り解析する機能を提供します。スクリプトを実行する際に指定した引数を解析します。argsMap プロパティにそれらの設定の追加します。 |
_GrailsTest | すべてのテスト実行に使用するコードが含まれています。他の種類のテストを追加する際に便利です。 |
_GrailsRun | アプリケーションを起動させるために必要な機能を提供します。通常は(runApp/runAppHttps )から、またはWARファイル(runWar/runWarHttps )から実行します。 |
スクリプトアーキテクチャ Script architecture
./scripts/FunctionalTests.groovy:includeTargets << new File("${basedir}/scripts/_FunctionalTests.groovy")
target(default: "Runs the functional tests for this project.") { depends(runFunctionalTests) }
./scripts/_FunctionalTests.groovy:
includeTargets << grailsScript("_GrailsTest")
target(runFunctionalTests: "Run functional tests.") { depends(...) … }
- 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 イベントを取得する
イベントハンドラを定義する Defining event handlers
_Events.groovy
. Grails searches for these scripts in the following locations:_Events.groovy
という名称のスクリプトで定義します。Grailsは次の場所からスクリプトを検索します:USER_HOME/.grails/scripts
- user-specific event handlersPROJECT_HOME/scripts
- applicaton-specific event handlersPLUGINS_HOME/*/scripts
- plugin-specific event handlersGLOBAL_PLUGINS_HOME/*/scripts
- event handlers provided by global plugins
USER_HOME/.grails/scripts
- ユーザー固有のイベントハンドラPROJECT_HOME/scripts
- アプリケーション固有のイベントハンドラPLUGINS_HOME/*/scripts
- プラグイン固有のイベントハンドラGLOBAL_PLUGINS_HOME/*/scripts
- グローバルプラグインによって提供されているイベントハンドラ
_Events.groovy
file._Events.groovy
ファイルにそれらを宣言するだけです。_Events.groovy
, with a name beginning with "event". The following example can be put in your /scripts directory to demonstrate the feature:_Events.groovy
を記述して、/scripts ディレクトリに配置することによって、イベントハンドラを実装することができます:eventCreatedArtefact = { type, name -> println "Created $type $name" }eventStatusUpdate = { msg -> println msg }
eventStatusFinal = { msg -> println msg }
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:eventCreatedArtefact
、eventStatusUpdate
、eventStatusFinal
。Grailsはいくつかの標準的なイベントを提供しています。詳細はコマンドラインリファレンスガイドを参照してください。たとえば、 compileコマンドは、次のようなイベントを発行させます。
CompileStart
- Called when compilation starts, passing the kind of compile - source or testsCompileEnd
- Called when compilation is finished, passing the kind of compile - source or tests
CompileStart
- sourceまたはtestsコンパイル開始時に発行されます。CompileEnd
- sourceまたはtestsコンパイル終了時に発行されます。
イベントトリガー Triggering events
includeTargets << grailsScript("_GrailsEvents")event("StatusFinal", ["Super duper plugin action complete!"])
共通イベント Common Events
Event | Parameters | Description |
---|---|---|
StatusUpdate | message | Passed a string indicating current script status/progress |
StatusError | message | Passed a string indicating an error message from the current script |
StatusFinal | message | Passed a string indicating the final script status message, i.e. when completing a target, even if the target does not exit the scripting environment |
CreatedArtefact | artefactType,artefactName | Called when a create-xxxx script has completed and created an artefact |
CreatedFile | fileName | Called whenever a project source filed is created, not including files constantly managed by Grails |
Exiting | returnCode | Called when the scripting environment is about to exit cleanly |
PluginInstalled | pluginName | Called after a plugin has been installed |
CompileStart | kind | Called when compilation starts, passing the kind of compile - source or tests |
CompileEnd | kind | Called when compilation is finished, passing the kind of compile - source or tests |
DocStart | kind | Called when documentation generation is about to start - javadoc or groovydoc |
DocEnd | kind | Called when documentation generation has ended - javadoc or groovydoc |
SetClasspath | rootLoader | Called 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. |
PackagingEnd | none | Called at the end of packaging (which is called prior to the Tomcat server being started and after web.xml is generated) |
イベント | パラメータ | 説明 |
---|---|---|
StatusUpdate | message | 実行されているスクリプトのステータス、進捗メッセージを知らせる |
StatusError | message | 実行されているスクリプトのエラーメッセージを 知らせる |
StatusFinal | message | スクリプトの終了時に最終メッセージを知らせる。 スクリプトによっては完全終了時ではなく、コマ ンドの終了時に動作する |
CreatedArtefact | artefactType,artefactName | create-xxxxなどのアーティファクト生成スクリプトが、アーティファクトの生成完了時にアーティ ファクトタイプとアーティファクト名を知らせる |
CreatedFile | fileName | ファイルがスクリプトによって生成されたときに ファイル名を知らせる |
Exiting | returnCode | スクリプトが正常に終了したときに終了コードを 知らせる |
PluginInstalled | pluginName | プラグインのインストールが終了した後にプラグイン 名を知らせる |
CompileStart | kind | コンパイル開始時にコンパイルする種類(source または tests)を知らせる |
CompileEnd | kind | コンパイル終了時にコンパイルした種類(source または tests)を知らせる |
DocStart | kind | ドキュメント生成時に、どのドキュメント生成(javadoc または groovydoc)が開始するかを知らせる |
DocEnd | kind | ドキュメント生成完了時に、どのドキュメント生成(javadoc または groovydoc)が完了したかを知らせる |
SetClasspath | rootLoader | クラスパス初期化中にGrailsRootLoader が渡されるので、「rootLoader.addURL( … )」でクラスをGrailsRootLoader に追加できる |
PackagingEnd | none | Grailsアプリケーションのパッケージング完了時 (web.xml生成後、Tomcatサーバ起動前)に呼び出される |
5.6 ビルドのカスタマイズ
初期値 The defaults
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
クラスです。このクラスは、どこにコンパイルされるのか、アプリケーションが何に依存関係を持っているのか、どのような設定を保持しているのか、を制御します。Property | Config option | Default value |
---|---|---|
grailsWorkDir | grails.work.dir | $USER_HOME/.grails/<grailsVersion> |
projectWorkDir | grails.project.work.dir | <grailsWorkDir>/projects/<baseDirName> |
classesDir | grails.project.class.dir | <projectWorkDir>/classes |
testClassesDir | grails.project.test.class.dir | <projectWorkDir>/test-classes |
testReportsDir | grails.project.test.reports.dir | <projectWorkDir>/test/reports |
resourcesDir | grails.project.resource.dir | <projectWorkDir>/resources |
projectPluginsDir | grails.project.plugins.dir | <projectWorkDir>/plugins |
globalPluginsDir | grails.global.plugins.dir | <grailsWorkDir>/global-plugins |
verboseCompile | grails.project.compile.verbose | false |
プロパティ | 設定オプション | 初期値 |
---|---|---|
grailsWorkDir | grails.work.dir | $USER_HOME/.grails/<grailsVersion> |
projectWorkDir | grails.project.work.dir | <grailsWorkDir>/projects/<baseDirName> |
classesDir | grails.project.class.dir | <projectWorkDir>/classes |
testClassesDir | grails.project.test.class.dir | <projectWorkDir>/test-classes |
testReportsDir | grails.project.test.reports.dir | <projectWorkDir>/test/reports |
resourcesDir | grails.project.resource.dir | <projectWorkDir>/resources |
projectPluginsDir | grails.project.plugins.dir | <projectWorkDir>/plugins |
globalPluginsDir | grails.global.plugins.dir | <grailsWorkDir>/global-plugins |
verboseCompile | grails.project.compile.verbose | false |
BuildSettings
class has some other properties too, but they should be treated as read-only:BuildSettings
クラスは、他にもいくつかの読み取り専用のプロパティを持っています:
Property | Description |
---|---|
baseDir | The location of the project. |
userHome | The user's home directory. |
grailsHome | The location of the Grails installation in use (may be null ). |
grailsVersion | The version of Grails being used by the project. |
grailsEnv | The current Grails environment. |
config | The 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 . |
compileDependencies | A list of compile-time project dependencies as File instances. |
testDependencies | A list of test-time project dependencies as File instances. |
runtimeDependencies | A list of runtime-time project dependencies as File instances. |
プロパティ | 説明 |
---|---|
baseDir | プロジェクトの場所。 |
userHome | ユーザーのホームディレクトリ。 |
grailsHome | 使用中のGrailsのインストール先(null の場合あり)。 |
grailsVersion | プロジェクトで使用されているGrailsのバージョン。 |
grailsEnv | 現在のGrails環境。 |
config | プロジェクトの BuildConfig.groovy に定義された設定。ランタイム時と同様にプロパティにアクセスできます: grailsSettings.config.foo.bar.hello |
compileDependencies | コンパイル時のプロジェクト依存関係のFileインスタンスのリスト。 |
testDependencies | テスト時のプロジェクト依存関係のFileインスタンスのリスト。 |
runtimeDependencies | 実行時のプロジェクト依存関係のFileインスタンスのリスト。 |
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.BuildSettings
のインスタンスのgrailsSettingspスクリプト変数を介して利用可能です。他のコードからも
grails.util.BuildSettingsHolder@クラスを使用してアクセスすることができます。でもこれは推奨されません。初期値を上書きする Overriding the defaults
grails -Dgrails.project.work.dir=work compile
grails-app/conf/BuildConfig.groovy
file:grails-app/conf/BuildConfig.groovy
に記述します:
grails.project.work.dir = "work"
BuildConfig.groovy
file, which in turn takes precedence over the default values.BuildConfig.groovy
ファイルの設定よりも優先順位が高いので、システムプロパティの値が設定されます。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.BuildConfig.groovy
ファイルは、grails-app/conf/Config.groovy
と兄妹関係にあります。前者は、ビルド時にのみ影響を及ぼすオプションを含んでいるのに対して、後者はアプリケーションの実行時に影響を与えるオプションを含んでいます。設定オプションは、1つめの表で示したオプション以外にも、サーブレットコンテナを動かすポート指定や、WARファイルにどのファイルを格納するかを決定する指定など、他にも指定可能なビルド設定が存在します。使用可能なビルド設定 Available build settings
Name | Description |
---|---|
grails.server.port.http | Port to run the embedded servlet container on ("run-app" and "run-war"). Integer. |
grails.server.port.https | Port to run the embedded servlet container on for HTTPS ("run-app --https" and "run-war --https"). Integer. |
grails.config.base.webXml | Path to a custom web.xml file to use for the application (alternative to using the web.xml template). |
grails.compiler.dependencies | Legacy 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.patterns | A 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.nameSuffix | By 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.file | A 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.dependencies | A closure containing "fileset()" entries that allows you complete control over what goes in the WAR's "WEB-INF/lib" directory. |
grails.war.copyToWebApp | A 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.resources | A 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.xml | The location to generate Grails' web.xml to |
名前 | 説明 |
---|---|
grails.server.port.http | 組み込みのサーブレットコンテナを実行するポート番号。("run-app" と "run-war") |
grails.server.port.https | HTTPS用の組み込みのサーブレットコンテナを実行するポート番号。("run-app --https"と"run-war --https") |
grails.config.base.webXml | アプリケーションで使用するカスタムのweb.xmlファイルへのパス。(web.xmlテンプレートを使用しない場合) |
grails.compiler.dependencies | コンパイラのクラスパスに依存関係を追加する。"fileset()"を含んでいるクロージャに設定。 |
grails.testing.patterns | テストに含まれるファイルを制御するためのAntパスのパターンリスト。パターンは、次のgrails.testing.nameSuffixに設定されているテストケースのサフィックス以外。 |
grails.testing.nameSuffix | デフォルトでは、テストは"Tests"のサフィックスが設定されていますが、好きなようにオプション設定を変更することができます。 |
grails.project.war.file | 生成されるWARファイルの名称(拡張子を含む)のファイルパス。例として、"target/my-app.war" 等。 |
grails.war.dependencies | WARファイルの"WEB-INF/lib"階層に含む内容を、クロージャ内の"fileset()"でコントロール。 |
grails.war.copyToWebApp | WARのルートディレクトリ階層に含む内容を、クロージャ内の"fileset()"でコントロール。 |
grails.war.resources | 最初の引数としてステージングディレクトリの場所を受け取れるクロージャを指定。クロージャ内でAntタスクを使用することで、WAR化される前にステージングディレクトリの内容を変更する事ができます。 |
grails.project.web.xml | Grailsがweb.xmlを生成する場所の指定。 |
リローディングエージェントキャッシュディレクトリ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
Antへの統合 Ant Integration
build.xml
file but you can generate one with the integrate-with command:build.xml
を生成しません。integrate-withコマンドを使用して生成することが可能です。
grails integrate-with --ant
build.xml
file containing the following targets:build.xml
ファイルには、次のターゲットが含まれています:
clean
- Cleans the Grails applicationcompile
- Compiles your application's source codetest
- Runs the unit testsrun
- Equivalent to "grails run-app"war
- Creates a WAR filedeploy
- Empty by default, but can be used to implement automatic deployment
clean
- Grailsアプリケーションをクリーンします。compile
- アプリケーションのソースコードをコンパイルします。test
- ユニットテストを実行します。run
- Grailsの"run-app"コマンド相当を実行します。war
- WARファイルを作成します。deploy
- デフォルトでは空ですが、自動配備を実装することができます。
ant war
<taskdef name="grailsTask" classname="grails.ant.GrailsTask" classpathref="grails.classpath"/>
Attribute | Description | Required |
---|---|---|
home | The location of the Grails installation directory to use for the build. | Yes, unless classpath is specified. |
classpathref | Classpath 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. |
script | The name of the Grails script to run, e.g. "TestApp". | Yes. |
args | The arguments to pass to the script, e.g. "-unit -xml". | No. Defaults to "". |
environment | The Grails environment to run the script in. | No. Defaults to the script default. |
includeRuntimeClasspath | Advanced setting: adds the application's runtime classpath to the build classpath if true. | No. Defaults to true . |
属性 | 説明 | 必須 |
---|---|---|
home | ビルドに使用するGrailsのインストールディレクトリの場所。 | パスが指定されている場合を除き必須です。 |
classpathref | Grailsがロードする基点となるクラスパス。"grails-bootstrap"を含めなければなりません。また、"grails-scripts"を含めるべきです。 | home が設定されていなかったり、classpath 要素を使う場合は必須です。 |
script | Grailsスクリプトの実行名。例えば "TestApp"。 | 必須です。 |
args | スクリプトに渡す引数。例えば "-unix -xml"。 | 必須ではありません。デフォルトは "" です。 |
environment | スクリプト実行時のGrails環境変数。 | 必須ではありません。デフォルトはスクリプトのデフォルトになります。 |
includeRuntimeClasspath | 高度な設定です。 trueの場合、アプリケーション実行時クラスパスをクラスパスに追加します。 | 必須ではありません。 デフォルトはtrue です。 |
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 inruntimeClasspath
.
classpath
- ビルド時のクラスパス。(GantとGrailsスクリプトロード時に使用)compileClasspath
- アプリケーションコンパイル時のクラスパス。runtimeClasspath
- アプリケーションとWARパッケージ実行時のクラスパス。通常compileClasspath
に全てが含まれます。testClasspath
- コンパイル時と、テスト実行時のクラスパス。通常runtimeClasspath
に全てが含まれます。
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.home
を利用しており、自分自身の依存関係をlib
ディレクトリに設定している場合は、これらを使う必要はありません。こららの利用例としては、生成された新しいアプリケーションのAntビルドファイルを見てみましょう。Maven統合 Maven Integration
準備 Preparation
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:既定のmvnコマンド設定ではGrails環境で実行するための十分なメモリを供給できません。パフォーマンス低下を防止するため、次の環境変数を追加することをお勧めします:
export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256"
GrailsのMavenのプロジェクトを作成する Creating a Grails Maven Project
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
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
のバージョンを同期します。compile
- Compiles a Grails projectpackage
- 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 cachetest
- Runs the tests of a Grails projectclean
- Cleans the Grails project
compile
- Grailsプロジェクトをコンパイルpackage
- GrailsプロジェクトのWARファイルをビルドするinstall
- WARファイル(又はプラグインの場合はZIPかJAR)をビルドしてMavenローカルキャッシュにインストールしますtest
- Grailsプロジェクトのテストを実行しますclean
- Grailsプロジェクトをクリーンします
grails:create-controller
- Calls the create-controller commandgrails:create-domain-class
- Calls the create-domain-class commandgrails:create-integration-test
- Calls the create-integration-test commandgrails:create-pom
- Creates a new Maven POM for an existing Grails projectgrails:create-script
- Calls the create-script commandgrails:create-service
- Calls the create-service commandgrails:create-taglib
- Calls the create-tag-lib commandgrails:create-unit-test
- Calls the create-unit-test commandgrails:exec
- Executes an arbitrary Grails command line scriptgrails:generate-all
- Calls the generate-all commandgrails:generate-controller
- Calls the generate-controller commandgrails:generate-views
- Calls the generate-views commandgrails:install-templates
- Calls the install-templates commandgrails:list-plugins
- Calls the list-plugins commandgrails:package
- Calls the package commandgrails:run-app
- Calls the run-app command
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コマンドを呼び出します
mvn grails:help
mvn grails:help
を実行してください。Archetypeを使用したGrails Mavenプロジェクトの作成 Creating a Grails Maven Project using the Archetype
mvn archetype:generate -DarchetypeGroupId=org.grails \ -DarchetypeArtifactId=grails-maven-archetype \ -DarchetypeVersion=2.1.0.RC1 \ -DgroupId=example -DartifactId=my-app
<plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin>
<plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin>
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プラグインを使用する場合は、リモートリポジトリの定義にリポジトリが追加されている必要があります。
<repository> <id>grails-plugins</id> <name>grails-plugins</name> <url>http://repo.grails.org/grails/plugins</url> </repository>
pom.xml
file:pom.xml
ファイルに、プラグイン依存定義を行います:<dependency> <groupId>org.grails.plugins</groupId> <artifactId>database-migration</artifactId> <version>1.1</version> <scope>runtime</scope> <type>zip</type> </dependency>
type
element must be set to zip
.type
エレメントの定義は zip
となる部分です。Grailsフォーク実行 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:
<plugin> <groupId>org.grails</groupId> <artifactId>grails-maven-plugin</artifactId> <version>${grails.version}</version> <configuration> <!-- Whether for Fork a JVM to run Grails commands --> <fork>true</fork> </configuration> <extensions>true</extensions> </plugin>
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 --> <fork>true</fork> <forkDebug>true</forkDebug>
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 {
…
mavenLocal()
}
}
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.
Grailsコマンドをフェーズに追加する Adding Grails commands to phases
<plugin> <groupId>org.grails</groupId> <artifactId>grails-maven-plugin</artifactId> <version>2.1.0.RC2</version> <extensions>true</extensions> <executions> <execution> <goals> … </goals> </execution> <!-- Add the "functional-tests" command to the "integration-test" phase --> <execution> <id>functional-tests</id> <phase>integration-test</phase> <goals> <goal>exec</goal> </goals> <configuration> <command>functional-tests</command> </configuration> </execution> </executions> </plugin>
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
GrailsのMavenプロジェクトのデバッグ Debugging a Grails Maven Project
mvnDebug grails:run-app
MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
mvn grails:run-app
問題提起 Raising issues
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:etc...
6 O/Rマッピング (GORM)
ドメインクラスは業務アプリケーションの中心です。 それらは業務プロセスについての状態や振る舞いを保持します。 また、それらは1対1、1対多、多対多などの関連を通して結びつけられます。
GORMは、Grailsのオブジェクトリレーショナルマッピング(ORM)の実装です。 その裏では、広く使われていて柔軟性の高いオープンソースORMであるHibernate 3を利用しています。 Grailsの規約と、静的・動的型付けというGroovyのダイナミックな特性のおかげで、Grailsのドメインクラスに必要となる設定はほとんどありません。
GrailsのドメインクラスをJavaで書くこともできます。 Javaでドメインクラスを書いて、動的な永続化メソッドも使えるようにする方法については、GrailsとHibernateのセクションを参照してください。
以下は、GORMのサンプルコードです:
def book = Book.findByTitle("Groovy in Action")book .addToAuthors(name:"Dierk Koenig") .addToAuthors(name:"Guillaume LaForge") .save()
6.1 クイックスタートガイド
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.パッケージ名を指定しない場合、自動的にアプリケーション名をパッケージ名として使用します。
grails-app/domain/helloworld/Person.groovy
such as the one below:grails-app/domain/helloworld/Person.groovy
に以下のようなドメインクラスを作成します。package helloworldclass 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"が設定されている場合は、ドメインクラスに対応したデータベースのテーブルを自動的に作成/修正します。
class Person { String name Integer age Date lastVisit }
grails console
6.1.1 基本CRUD
作成
def p = new Person(name: "Fred", age: 40, lastVisit: new Date()) p.save()
参照
id
property to your domain class which you can use for retrieval:id
プロパティをドメインクラスの永続化時に付与します。このid
によって検索時にドメインクラスを一意に識別することができます。def p = Person.get(1) assert 1 == p.id
Person
object back from the database.Person
オブジェクトを返します。
def p = Person.read(1)
def p = Person.load(1)
更新
def p = Person.get(1)
p.name = "Bob"
p.save()
削除
def p = Person.get(1) p.delete()
6.2 GORMでのドメインモデリング
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.Book
クラスはタイトル、出版日、ISBNコードなどを持つでしょう。以降のいくつかの節でGORM内でどのようにドメインをモデル化すればよいかをお見せします。grails create-domain-class org.bookstore.Book
grails-app/domain/org/bookstore/Book.groovy
:grails-app/domain/org/bookstore/Book.groovy
クラスが作成されます。package org.bookstoreclass Book { }
book
(the same name as the class). This behaviour is customizable through the ORM Domain Specific Languagebook
テーブル(作成したクラスと同じ名前)と対応付けられます。この動作はORMのドメイン固有言語によってカスタマイズできます。package org.bookstoreclass Book { String title Date releaseDate String ISBN }
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.releaseDate
プロパティはrelease_date
カラムに対応付けられます。SQLの型はJavaの型から自動的に判別されますが、ConstraintsやORMのドメイン固有言語によってカスタマイズすることができます。
6.2.1 GORMでの関連
6.2.1.1 多対1、1対1 (Many-to-One, One-to-one)
Example A
class Face { Nose nose }
class Nose { }
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):Face
からNose
への単方向の多対1の関連が存在しています。この関連を双方向にする場合は、もう片方のクラスを次のように定義します。(加えて本項最後の関連の両端をコントロールするの項を参照してください。)Example B
class Face { Nose nose }
class Nose {
static belongsTo = [face:Face]
}
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
:belongsTo
を設定することで、Nose
"が"Face
に"属している"ということを表現しています。結果として、Nose
インスタンスを保持するFace
インスタンスを作成し、そのFace
インスタンスをsave、deleteした場合、GORMはNose
のsave、deleteを自動的に行います。別の言い方をすれば、saveとdeleteがFace
から関連したNose
へcascadeします。new Face(nose:new Nose()).save()
Face
:Face
が保存されず、意図しない動作となる点に注意してください。new Nose(face:new Face()).save() // will cause an error
new Nose(face:new Face()).save() // 意図しない動作 Noseは保存されるが、Faceは保存されない
Face
instance, the Nose
will go too:Face
インスタンスを削除すると、Nose
も削除される例です:def f = Face.get(1) f.delete() // both Face and Nose deleted
def f = Face.get(1) f.delete() // FaseとNose両方が削除される
hasOne
property on the owning side, e.g. Face
:hasOne
プロパティを使います。Face
の例:Example C
class Face {
static hasOne = [nose:Nose]
}
class Nose { Face face }
nose
table inside a column called face_id
. Also, hasOne
only works with bidirectional relationships.face
テーブルにnose
テーブルへの外部キーが生成されますが、このプロパティを使用すると外部キーが作成されるテーブルが逆になる点に注意してください。この例だと、nose
テーブルにface_id
カラムが追加されます。hasOne
も双方向の関連としてのみ動作します。class Face { static hasOne = [nose:Nose]static constraints = { nose unique: true } }
class Nose { Face face }
関連の両端をコントロールする
class Person { String name Person parentstatic belongsTo = [ supervisor: Person ]
static constraints = { supervisor nullable: true } }
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.parent
プロパティとsupervisor
プロパティを2方向の同じ関連として扱います。つまり、Person
インスタンスAのparent
プロパティにPerson
インスタンスBを格納した時、Grailsは自動的にPerson
インスタンスBのsupervisor
プロパティにPerson
インスタンスAを格納します。 これは期待した動作かもしれません。しかしクラスを見れば、むしろ2つの単方向の関連を持つことを期待するでしょう。mappedBy
property:mappedBy
プロパティを使用して特定の関連が単方向であることを示すことができます:class Person { String name Person parentstatic belongsTo = [ supervisor: Person ]
static mappedBy = [ supervisor: "none", parent: "none" ]
static constraints = { supervisor nullable: true } }
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.mappedBy
プロパティは多対1と1対1関連だけに限定されていません。次項でわかるように、1対多と多対多の関連の場合も動作します。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"はプロパティ名としては珍しい名前のため、特に気にする必要はないでしょう。
6.2.1.2 1対多 (One-to-many)
Author
, has many instances of another class, example Book
. With Grails you define such a relationship with the hasMany
setting:
Author
のような1つのクラス、Book
のような他クラスのインスタンスを複数保持します。
GrailsではhasMany
の設定でこの関連を定義します。class Author { static hasMany = [books: Book]String name }
class Book {
String title
}
The ORM DSL allows mapping unidirectional relationships using a foreign key association instead
ORM DSLでは代わりに外部キーの参照を使用した単方向関連の設定もできます。
java.util.Set
into the domain class based on the hasMany
setting. This can be used to iterate over the collection:
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"フェッチを指定してください。
belongsTo
is also specified:
belongsTo
が指定されるまでカスケードされません。class Author { static hasMany = [books: Book]String name }
class Book { static belongsTo = [author: Author] String title }
mappedBy
to specify which the collection is mapped:
mappedBy
を使ってください。class Airport { static hasMany = [flights: Flight] static mappedBy = [flights: "departureAirport"] }
class Flight { Airport departureAirport Airport destinationAirport }
class Airport { static hasMany = [outboundFlights: Flight, inboundFlights: Flight] static mappedBy = [outboundFlights: "departureAirport", inboundFlights: "destinationAirport"] }
class Flight { Airport departureAirport Airport destinationAirport }
6.2.1.3 多対多 (Many-to-many)
hasMany
on both sides of the relationship and having a belongsTo
on the owned side of the relationship:
hasMany
を定義し、関連の所有される側にbelongsTo
を付けることで、多対多の関連をサポートします。class Book { static belongsTo = Author static hasMany = [authors:Author] String title }
class Author { static hasMany = [books:Book] String name }
Author
, takes responsibility for persisting the relationship and is the only side that can cascade saves across.
Author
)は、関連の永続化の責務を持ちます。そして、この所有する側からのみ保存のカスケードが可能です。new Author(name:"Stephen King") .addToBooks(new Book(title:"The Stand")) .addToBooks(new Book(title:"The Shining")) .save()
Book
and not the authors!
Book
だけが保存されauthorsは保存されません!new Book(name:"Groovy in Action") .addToAuthors(new Author(name:"Dierk Koenig")) .addToAuthors(new Author(name:"Guillaume Laforge")) .save()
Grails' Scaffolding feature does not currently support many-to-many relationship and hence you must write the code to manage the relationship yourself
Grailsのスカッフォルドは現在、多対多の関連をサポートしていません。 そのため、関連を管理するコードは自分で書かなければなりません。
6.2.1.4 基本コレクション型
nicknames
association that is a Set
of String
instances:
String
のSet
であるnicknames
の関連を作成します。class Person { static hasMany = [nicknames: String] }
joinTable
argument:
joinTable
引数を使って、どのように結合テーブルにマップされるかを変更できます。class Person {static hasMany = [nicknames: String]
static mapping = { hasMany joinTable: [name: 'bunch_o_nicknames', key: 'person_id', column: 'nickname', type: "text"] } }
bunch_o_nicknames Table
--------------------------------------------- | person_id | nickname | --------------------------------------------- | 1 | Fred | ---------------------------------------------
6.2.2 GORMでのコンポジション
class Person { Address homeAddress Address workAddress static embedded = ['homeAddress', 'workAddress'] }class Address { String number String code }
If you define theAddress
class in a separate Groovy file in thegrails-app/domain
directory you will also get anaddress
table. If you don't want this to happen use Groovy's ability to define multiple classes per file and include theAddress
class below thePerson
class in thegrails-app/domain/Person.groovy
file
もしgrails-app/domain
ディレクトリ内に別のGroovyファイルとしてAddress
クラスを定義した場合は、以前と同じようにaddress
テーブルが作成されてしまいます。 これを避けたい場合は、1ファイルに複数のクラスを定義できるGroovyの能力を使い、grails-app/domain/Person.groovy
ファイルのPerson
クラスの下にAddress
クラスを含めてください。
6.2.3 GORMでの継承
class Content {
String author
}
class BlogEntry extends Content {
URL url
}
class Book extends Content { String ISBN }
class PodCast extends Content { byte[] audioStream }
Content
class and then various child classes with more specific behaviour.
Content
クラスと個別の振る舞いを持ったさまざまな子クラスを定義しています。Considerations
考慮すべきこと
class
so the parent class (Content
) and its subclasses (BlogEntry
, Book
etc.), share the same table.
class
という名前の識別カラムと共にtable-per-hierarchyマッピングを使います。
これは親クラス(Content
)と、その子クラス(BlogEntry
やBook
など)が同じテーブル上に格納されます。Polymorphic Queries
ポリモーフィズムなクエリ
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 authordef podCasts = PodCast.list() // list only podcasts
6.2.4 セット、リスト、マップ
オブジェクトのセット
java.util.Set
which is an unordered collection that cannot contain duplicates. In other words when you have:
java.util.Set
になります。
これは、順序を持たないコレクションで、重複要素を含めません。
言い換えると、次のようなドメインクラスがあるとき:class Author {
static hasMany = [books: Book]
}
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
:
books
プロパティはjava.util.Set
になる、ということです。
セットはユニーク性を保証しますが、順序は保証しません。
これでは都合が悪い場合もあるかもしれません。
独自の順序を持つにはセットをSortedSet
に設定します:class Author {SortedSet books
static hasMany = [books: Book] }
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) } }
Lists of Objects
オブジェクトのリスト
List
:
class Author {List books
static hasMany = [books: Book] }
author.books[0] // get the first book
books_idx
column where it saves the index of the elements in the collection to retain this order at the database level.
books_idx
カラムを作成して、コレクション内の要素のインデックスを保存します。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') book.save() author.addToBooks(book)// Do it this way instead. def book = new Book(title: 'Misery') author.addToBooks(book) author.save()
オブジェクトのバッグ(Bag)
ユニークや順序が必要の無い場合は(また明示的に自分で管理する場合)、HibernateのBag型をコレクションマップとして使用できます。
Collection
:Collection
型として定義します。class Author {Collection books
static hasMany = [books: Book] }
Set
or a List
.Set
または@Listよりメモリ使用量が少なくパフォーマンスが良くなります。オブジェクトのマップ
class Author { Map books // map of ISBN:book names }def a = new Author() a.books = ["1590597583":"Grails Book"] a.save()
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()
hasMany
property defines the type of the elements within the Map. The keys for the map must be strings.hasMany
プロパティで、Mapのエレメントの型を定義します。マップのキーは必ず文字列にしてください。A Note on Collection Types and Performance
コレクション型とパフォーマンスについて
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.
Set
型は重複を許容しません。
Set
の関連へエントリを追加するときに、ユニーク性を保証するため、Hibernateはデータベースからすべての関連を読み込まなければなりません。
もし関連のエントリの数が大量の場合、パフォーマンスの点でコストがかかりすぎる可能性があります。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 book.save()
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:
Author
と関連する大量のBook
インスタンスが与えられたとき、下のようなコードを書いてしまうとパフォーマンスに重大な影響があります:def book = new Book(title:"New Grails Book") def author = Author.get(1) author.addToBooks(book) author.save()
6.3 永続化の基礎
トランザクション内における遅延書き込み
6.3.1 保存と更新
def p = Person.get(1) p.save()
flush
を使って、以下のようにしてください:def p = Person.get(1)
p.save(flush: true)
def p = Person.get(1) try { p.save(flush: true) } catch (org.springframework.dao.DataIntegrityViolationException e) { // deal with exception }
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()
メソッドは、デフォルトではnull
を返します。例外を発生させたい場合には、名前付き引数failOnError
を使って、以下のようにしてください:
def p = Person.get(1) try { p.save(failOnError: true) } catch (ValidationException e) { // deal with exception }
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.failOnError
引数を省略した時のデフォルト動作は、Config.groovy
の設定により変更することができます。具体的な変更方法は「設定」の章に記載されています。ただし、エンドユーザの入力値を格納しているドメインインスタンスをsaveするケースでは、バリデーション例外が発生する可能性は非常に高く、かつ、例外をエンドユーザに直接表示することは避けたいと思うことが多いでしょう。その点を踏まえて、デフォルト動作を決定するようにしてください。6.3.2 オブジェクトの削除
def p = Person.get(1) p.delete()
flush
argument:flush
を使うことができます:def p = Person.get(1)
p.delete(flush: true)
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) }
deleteAll
method as deleting data is discouraged and can often be avoided through boolean flags/logic.deleteAll
メソッドは提供しておらず、そのような削除の方法は推奨されていません。代わりに、削除されたかどうか判定するためのフラグやロジックを用意するなどの方法を検討してください。Customer.executeUpdate("delete Customer c where c.name = :oldName", [oldName: "Fred"])
6.3.3 カスケード更新削除を理解する
belongsTo
setting which controls which class "owns" a relationship.belongsTo
設定については覚えておく必要があります。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.belongsTo
を定義することで、所有者のクラスから、所有されているクラス(関連の他方)に対して更新がカスケードします。また、多対1、1対1、1対多の場合は、削除も同様にカスケードします。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
コレクション内に新しいインスタンスが有れば保存が自動的にカスケードします)。class Airport { String name static hasMany = [flights: Flight] }
class Flight { String number static belongsTo = [airport: Airport] }
Airport
and add some Flight
s to it I can save the Airport
and have the updates cascaded down to each flight, hence saving the whole object graph:Airport
インスタンスを生成し、そこにFlight
インスタンスをいくつか追加してみます。その後にAirport
インスタンスを保存すると、各Flight
インスタンスにも保存がカスケードし、結果として、Airport
を起点とするオブジェクトグラフ全体が保存されることになります:new Airport(name: "Gatwick") .addToFlights(new Flight(number: "BA3430")) .addToFlights(new Flight(number: "EZ0938")) .save()
Airport
all Flight
s associated with it will also be deleted:Airport
インスタンスを削除してみます。すると、削除がカスケードするため、関連している全てのFlight
インスタンスも合わせて削除されます:def airport = Airport.findByName("Gatwick")
airport.delete()
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)も参照してください。双方向1対多関係でbelongsToが定義されている場合
class A { static hasMany = [bees: B] }
class B { static belongsTo = [a: A] }
belongsTo
then the cascade strategy is set to "ALL" for the one side and "NONE" for the many side.belongsTo
が定義されている場合は、Hibernateのカスケード戦略として「1」側に"ALL"が、「多」側に"NONE"が、それぞれ設定されます。単方向1対多関係の場合
class A { static hasMany = [bees: B] }
class B { }
belongsTo
が定義されていない場合は、Hibernateのカスケード戦略として"SAVE-UPDATE"が設定されます。双方向1対多関係でbelongsToが定義されていない場合
class A { static hasMany = [bees: B] }
class B { A a }
belongsTo
then the cascade strategy is set to "SAVE-UPDATE" for the one side and "NONE" for the many side.belongsTo
が定義されていない場合は、Hibernateのカスケード戦略として「1」側に"SAVE-UPDATE"が、「多」側に"NONE"が、それぞれ設定されます。単方向1対1関係でbelongsToが定義されている場合
class A { }
class B { static belongsTo = [a: 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)belongsTo
が定義されている場合は、Hibernateのカスケード戦略として、所有者側(上記の例ではAがBを所有しているのでA)に"ALL"が、belongsTo
が定義されている側(上記の例ではB)に"NONE"が、それぞれ設定されます。6.3.4 EagerフェッチとLazyフェッチ
class Airport { String name static hasMany = [flights: Flight] }
class Flight { String number Location destination static belongsTo = [airport: Airport] }
class Location { String city String country }
def airport = Airport.findByName("Gatwick") for (flight in airport.flights) { println flight.destination.city }
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).Airport
インスタンスを取得するためのSQLを発行します。
次に、airport.flights
にアクセスしようとして、そのAirport
が所有しているFlight
インスタンスの集合を取得するためのSQLを発行します。
それから、 airport.flights
内に格納されている各Flight
インスタンスについて、そのフライトのdestination
を取得するために、 それぞれ 1回のSQLを発行します。以上をまとめると、上記コード実行のために N+1 回のクエリーが発行されることになります(初回のAirport
インスタンスを取得するためのクエリーを除く)。Eagerフェッチングのための設定
class Airport { String name static hasMany = [flights: Flight] static mapping = { flights lazy: false } }
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を使っていることに起因します。fetch: 'join'
for single-ended associations and lazy: false
for one-to-manys.fetch: 'join'
を、1対多関連ではlazy: false
を使うことを推奨します。mapping
に指定できるオプションについての詳しい情報はORM DSLの章に記載されています。一括フェッチングの利用
class Airport { String name static hasMany = [flights: Flight] static mapping = { flights batchSize: 10 } }
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:batchSize
引数が指定されています。この指定によって、flights
が保持している各Flight
インスタンスにアクセスするときに、10個単位で、一括して結果を取得するようになります。例えば、あるAirport
インスタンスが30個のFlight
インスタンスを保持しているとします。一括フェッチングが指定されていなければ、1つのFlight
インスタンスにつき1回のクエリーを発行するので、全Flight
インスタンスにアクセスするには、合計30個のクエリーが必要になります。一方、一括フェッチングが上記のように指定されていれば、10個のFlight
インスタンスを1回のクエリーで取得するようになるので、必要なクエリーの数は3回になります。すなわち、一括フェッチングは、lazyフェッチングの最適化の1手法と言うことができます。なお、一括フェッチングは、以下のように、クラスのレベルで指定することも可能です:class Flight {
…
static mapping = {
batchSize 10
}
}
6.3.5 悲観的ロックと楽観的ロック
楽観的ロック
version
column in the database that is incremented after each update.version
カラムにバージョン番号を格納して、レコードを更新する度に値をインクリメントします。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
version
カラムに格納されている値と、更新対象のインスタンスが保持しているversion
プロパティの値を比較します。
そして、2つの値が異なる場合にはStaleObjectException例外をスローします。
トランザクションが有効な場合は、この例外発生によって、トランザクションもロールバックします。def airport = Airport.get(10)try { airport.name = "Heathrow" airport.save(flush: true) } catch (org.springframework.dao.OptimisticLockingFailureException e) { // deal with exception }
Theversion
will only be updated after flushing the session.version
プロパティの値は、セッションをフラッシュしない限り更新されません。
悲観的ロック
def airport = Airport.get(10) airport.lock() // lock for update airport.name = "Heathrow" airport.save()
get()
and the call to lock()
.get()
メソッドを呼び出してからlock()
メソッドを呼び出す間に、他のスレッドがレコードを更新する可能性が残ってしまいます。
この問題を回避するために、getメソッドと同様にidを引数に取るstaticなlockメソッドが使えます:def airport = Airport.lock(10) // lock for update airport.name = "Heathrow" airport.save()
def airport = Airport.findByName("Heathrow", [lock: true])
def airport = Airport.createCriteria().get {
eq('name', 'Heathrow')
lock true
}
6.3.6 変更確認
isDirty
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()
は、今のところ関連のコレクションをチェックしません。
しかし、他のすべての永続化プロパティと関連をチェックします。
def airport = Airport.get(10) assert !airport.isDirty()airport.properties = params if (airport.isDirty('name')) { // do something based on changed name }
getDirtyPropertyNames
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 }
getPersistentValue
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でのクエリー
- Dynamic Finders
- Where Queries
- Criteria Queries
- Hibernate Query Language (HQL)
- ダイナミックファインダー
- Whereクエリー
- クライテリアクエリー
- Hibernateクエリー言語 (HQL)
インスタンスの一覧取得
def books = Book.list()
def books = Book.list(offset:10, max:20)
def books = Book.list(sort:"title", order:"asc")
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.sort
はソート対象にしたいドメインクラスのプロパティを指定します。order
はasc
であれば昇順(ascending)、desc
であれば降順(descending)となります。データベースのIDによる取得
def book = Book.get(23)
def books = Book.getAll(23, 93, 81)
6.4.1 ダイナミックファインダー
Book
class:Book
クラスの例をあげます。:class Book {
String title
Date releaseDate
Author author
}
class Author {
String name
}
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":
Book
クラスはtitle
やreleaseDate
、auther
などのプロパティを持ちます。これらのプロパティは"メソッド表現方式"を用いて、findByやfindAllByメソッド内で使用することができます。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)
メソッド表現方式によるメソッド名の指定
Book.findBy([Property][Comparator][Boolean Operator])?[Property][Comparator]
def book = Book.findByTitle("The Stand")book = Book.findByTitleLike("Harry Pot%")
Like
comparator, is equivalent to a SQL like
expression.title
が一致するものを検索します。2番目のLike
比較演算子を使ったクエリーは、SQLのlike
表現と同様の検索を行います。InList
- In the list of given valuesLessThan
- less than a given valueLessThanEquals
- less than or equal a give valueGreaterThan
- greater than a given valueGreaterThanEquals
- greater than or equal a given valueLike
- Equivalent to a SQL like expressionIlike
- Similar to aLike
, except case insensitiveNotEqual
- Negates equalityInRange
- Between thefrom
andto
values of a Groovy RangeRlike
- Performs a Regexp LIKE in MySQL or Oracle otherwise falls back toLike
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 thefrom
andto
values of a Groovy RangeRlike
- Performs a Regexp LIKE in MySQL or Oracle otherwise falls back toLike
Between
- 2つの値の範囲内である (2つのパラメータが必要)IsNotNull
- Nullではない (パラメータ不要)IsNull
- Nullである (パラメータ不要)
def now = new Date() def lastWeek = now - 7 def book = Book.findByReleaseDateBetween(lastWeek, now)books = Book.findAllByReleaseDateIsNull() books = Book.findAllByReleaseDateIsNotNull()
AND/ORによる複数条件
def books = Book.findAllByTitleLikeAndReleaseDateGreaterThan( "%Java%", new Date() - 30)
And
in the middle of the query to make sure both conditions are satisfied, but you could equally use Or
:And
を使いましたが、同様のやり方でOr
を使うこともできます:def books = Book.findAllByTitleLikeOrReleaseDateGreaterThan( "%Java%", new Date() - 30)
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.And
やOr
を使用して結合することができます。また、メソッド名があまりにも長くなりすぎてしまったときは、クエリーをCriteriaやHQLに変換することもできます。クエリーと関連
def author = Author.findByName("Stephen King")def books = author ? Book.findAllByAuthor(author) : []
Author
instance is not null we use it in a query to obtain all the Book
instances for the given Author
.Author
インスタンスがNullの場合は空の集合を返し、そうでない場合はパラメータに指定したAuthor
が持つ全てのBook
インスタンスを取得します。ページングとソート
def books = Book.findAllByTitleLike("Harry Pot%", [max: 3, offset: 2, sort: "title", order: "desc"])
6.4.2 Whereクエリー
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.where
メソッドはDetached Criteriaの拡張であり、コンパイル時に型チェックなどを実施することが出来るDSLクエリー言語を実現しています。また、where
メソッドはダイナミックファインダーより柔軟で、クライテリアよりは冗長ではないクエリー作成のメカニズムを提供します。基本の構文
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:where
メソッドはGroovyのコレクションの標準的なメソッドによく似たを受け取ります。このクロージャは標準的なGroovyの文法に従います。例えば以下の通りです。:def query = Person.where {
firstName == "Bart"
}
Person bart = query.find()
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:where
メソッドから返ってくるのはDetachedCriteria
のインスタンスです。つまり、この段階では特定のデータベース接続やセッションと紐づいているわけではありません。そのため、共通的なクエリーをクラスレベルで定義したい場合にもwhere
メソッドを追加して対応する事が出来ます。:class Person { static simpsons = where { lastName == "Simpson" } … } … Person.simpsons.each { println it.firstname }
findAll
and find
methods to accomplish this:findAll
やfind
メソッドの引数として指定してください。:def results = Person.findAll { lastName == "Simpson" } def results = Person.findAll(sort:"firstName") { lastName == "Simpson" } Person p = Person.find { firstName == "Bart" }
Operator | Criteria Method | Description |
---|---|---|
== | eq | Equal to |
!= | ne | Not equal to |
> | gt | Greater than |
< | lt | Less than |
>= | ge | Greater than or equal to |
<= | le | Less than or equal to |
in | inList | Contained within the given list |
==~ | like | Like a given string |
=~ | ilike | Case insensitive like |
比較演算子 | クライテリアのメソッド | 説明 |
---|---|---|
== | eq | 一致する |
!= | ne | 一致しない |
> | gt | より大きい |
< | lt | より小さい |
>= | ge | 以上 |
<= | le | 以下 |
in | inList | 指定されたリストのいずれかと一致する |
==~ | like | 指定された文字列とのLike比較 |
=~ | ilike | 指定された文字列とのLike比較(大文字小文字の違いを無視) |
def query = Person.where { (lastName != "Simpson" && firstName != "Fred") || (firstName == "Bart" && age > 9) } def results = query.list(sort:"firstName")
Pattern
object, in which case they map onto an rlike
query:like
とilike
メソッドにマッピングされます。もし右側がPattern
オブジェクトになっていれば、rlike
メソッドにマッピングされます。:
def query = Person.where { firstName ==~ ~/B.+/ }
Note that rlike
queries are only supported if the underlying database supports regular expressions
rlike
クエリーは正規表現をサポートしているデータベースでのみ利用できることに注意してください。
between
criteria query can be done by combining the in
keyword with a range:between
クライテリアクエリーはin
による範囲指定で同様の結果を得る事が出来ます。:def query = Person.where { age in 18..65 }
isNull
and isNotNull
style queries by using null
with regular comparison operators:isNull
やisNotNull
を条件にしたい場合、null
キーワードと比較演算子を使う事で条件指定する事が出来ます。:def query = Person.where {
middleName == null
}
クエリーの構成
where
method is a DetachedCriteria instance you can compose new queries from the original query:where
メソッドの戻り値はDetachedCriteriaインスタンスです。戻り値のDetachedCriteriaインスタンスを元に、さらに条件を追加したクエリーを作成することが出来ます。:def query = Person.where { lastName == "Simpson" } def bartQuery = query.where { firstName == "Bart" } Person p = bartQuery.find()
where
method unless it has been explicitly cast to a DetachedCriteria
instance. In other words the following will produce an error:DetachedCriteria
インスタンスとしてキャストされていない限り、where
メソッドのパラメータとして渡すことは出来ない事に注意してください。以下のような例ではエラーが発生します。:def callable = {
lastName == "Simpson"
}
def query = Person.where(callable)
import grails.gorm.DetachedCriteriadef callable = { lastName == "Simpson" } as DetachedCriteria<Person> def query = Person.where(callable)
as
keyword) to a DetachedCriteria instance targeted at the Person
class.as
キーワードを使えば、クロージャの定義をPerson
クラス向けのDetachedCriteriaインスタンスとしてキャストする事が出来ます。論理積、論理和と否定
||
and &&
) to form conjunctions and disjunctions:||
や&&
)を組み合わせる事が出来ます。:def query = Person.where { (lastName != "Simpson" && firstName != "Fred") || (firstName == "Bart" && age > 9) }
!
:!
を使って否定する事もできます。:def query = Person.where {
firstName == "Fred" && !(lastName == 'Simpson')
}
プロパティの比較クエリー
def query = Person.where { firstName == lastName }
Operator | Criteria Method | Description |
---|---|---|
== | eqProperty | Equal to |
!= | neProperty | Not equal to |
> | gtProperty | Greater than |
< | ltProperty | Less than |
>= | geProperty | Greater than or equal to |
<= | leProperty | Less than or equal to |
演算子 | クライテリアのメソッド | 説明 |
---|---|---|
== | eqProperty | 一致する |
!= | neProperty | 一致しない |
> | gtProperty | より大きい |
< | ltProperty | より小さい |
>= | geProperty | 以上 |
<= | leProperty | 以下 |
関連を利用したクエリー
def query = Pet.where { owner.firstName == "Joe" || owner.firstName == "Fred" }
def query = Person.where { pets { name == "Jack" || name == "Joe" } }
def query = Person.where { pets { name == "Jack" } || firstName == "Ed" }
def query = Person.where { pets.size() == 2 }
Operator | Criteria Method | Description |
---|---|---|
== | sizeEq | The collection size is equal to |
!= | sizeNe | The collection size is not equal to |
> | sizeGt | The collection size is greater than |
< | sizeLt | The collection size is less than |
>= | sizeGe | The collection size is greater than or equal to |
<= | sizeLe | The collection size is less than or equal to |
演算子 | クライテリアのメソッド | 説明 |
---|---|---|
== | sizeEq | コレクションのサイズが等しい |
!= | sizeNe | コレクションのサイズが等しくない |
> | sizeGt | コレクションのサイズより大きい |
< | sizeLt | コレクションのサイズより小さい |
>= | sizeGe | コレクションのサイズ以上 |
<= | sizeLe | コレクションのサイズ以下 |
サブクエリー
final query = Person.where {
age > avg(age)
}
Method | Description |
---|---|
avg | The average of all values |
sum | The sum of all values |
max | The maximum value |
min | The minimum value |
count | The count of all values |
property | Retrieves a property of the resulting entities |
メソッド | 説明 |
---|---|
avg | 全ての値の平均 |
sum | 全ての値の合計 |
max | 最大値 |
min | 最小値 |
count | 全ての値の個数 |
property | 結果のエンティティのプロパティを取得する。 |
of
method and passing in a closure containing the criteria:
of
メソッドを使い、クライテリアが含まれているクロージャを渡すことによって、追加のクライテリアを指定することが出来ます。:def query = Person.where { age > avg(age).of { lastName == "Simpson" } && firstName == "Homer" }
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":
property
サブクエリーが複数の結果を返すため、クライテリアは全ての結果との比較に利用されます。たとえば、以下の例では姓が"Simpson"である人よりも若い人を検索しています。:Person.where {
age < property(age).of { lastName == "Simpson" }
}
その他の機能
Method | Description |
---|---|
second | The second of a date property |
minute | The minute of a date property |
hour | The hour of a date property |
day | The day of the month of a date property |
month | The month of a date property |
year | The year of a date property |
lower | Converts a string property to upper case |
upper | Converts a string property to lower case |
length | The length of a string property |
trim | Trims a string property |
メソッド | 説明 |
---|---|
second | 日付プロパティの秒 |
minute | 日付プロパティの分 |
hour | 日付プロパティの時 |
day | 日付プロパティの日 |
month | 日付プロパティの月 |
year | 日付プロパティの年 |
lower | 文字列プロパティを小文字に変換 |
upper | 文字列プロパティを大文字に変換 |
length | 文字列プロパティの長さ |
trim | 文字列プロパティをトリムする |
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.
今のところ、これらの機能はプロパティか、ドメインクラスの関連のみで使用できます。例えば、サブクエリーの結果に対してこれらの機能を使用する事はできません。
def query = Pet.where { year(birthDate) == 2011 }
def query = Person.where { year(pets.birthDate) == 2009 }
バッチ更新と削除
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":
where
メソッドの呼び出しがDetachedCriteriaインスタンスを返却するため、バッチ更新や削除などの操作をバッチ操作を実行するためにwhere
クエリを使用する事が出来ます。例えば、以下のクエリーは"Bloggs"という姓を持っている全てのPersonを"Simpson"で更新します。: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.
バッチ操作では、関連を使用した結合クエリが許可されていないという制約に注意してください。
deleteAll
method:deleteAll
メソッドを使用する事が出来ます:def query = Person.where {
lastName == 'Simpson'
}
int total = query.deleteAll()
6.4.3 クライテリア
StringBuffer
.
StringBuffer
を使ってクエリ文字列を構築するより優れたやり方です。def c = Account.createCriteria() def results = c { between("balance", 500, 1000) eq("branch", "London") or { like("holderFirstName", "Fred%") like("holderFirstName", "Barney%") } maxResults(10) order("holderLastName", "desc") }
Account
objects in a List matching the following criteria:
Account
オブジェクトを最大10件検索します:balance
is between 500 and 1000branch
is 'London'holderFirstName
starts with 'Fred' or 'Barney'
balance
が500
から1000
の間であるbranch
がLondon
であるholderFirstName
がFred
かBarney
で始まっている
holderLastName
.
holderLastName
の降順でソートされます。Conjunctions and Disjunctions
論理積と論理和
or { }
block:
or { }
ブロックを使用し、クライテリアを論理和でグループ化できます。or { between("balance", 500, 1000) eq("branch", "London") }
and { between("balance", 500, 1000) eq("branch", "London") }
not { between("balance", 500, 1000) eq("branch", "London") }
Querying Associations
関連のクエリ
Account
class had many Transaction
objects:
Account
クラスが1対多の関連としてTransaction
オブジェクトを持っているとします:class Account {
…
static hasMany = [transactions: Transaction]
…
}
transactions
as a builder node:
transactions
を使いこの関連を問い合わせできます:def c = Account.createCriteria()
def now = new Date()
def results = c.list {
transactions {
between('date', now - 10, now)
}
}
Account
instances that have performed transactions
within the last 10 days.
You can also nest such association queries within logical blocks:
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)
}
}
}
Querying with Projections
プロジェクション(射影)を利用したクエリ
projections
ノードを定義します。
プロジェクションノードのメソッドは、HibernateのProjectionsクラスのメソッドに相当します。def c = Account.createCriteria()def numberOfBranches = c.get { projections { countDistinct('branch') } }
SQL Projections
SQLプロジェクション
// 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] } }
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によって提供されています。BOX
table.
BOX
テーブル内のデータを表すと考えてください。width | height |
---|---|
2 | 7 |
2 | 8 |
2 | 9 |
4 | 9 |
[[18, 14], [20, 16], [22, 18], [26, 36]]
Box
, perimeter and area.
Box
に対する全周と面積を表す、2つのプロジェクションされた値を含んでいます。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 exampleStandardBasicTypes.INTEGER
instead ofINTEGER
.
もしクライテリアクエリ内から参照できるスコープ内に前述の型定数と重複する名前の変数が宣言されている場合は、クライテリア中のコードは、DSLが提供する型定数ではなく、その変数を利用してしまうことに注意してください。 そのような場合は、完全修飾されたHibernateの型を指定することであいまいさを無くし衝突を回避できます。 例えば、INTEGER
の代わりにStandardBasicTypes.INTEGER
を指定します。
def results = c.list { projections { sqlProjection 'sum(width * height) as totalArea', 'totalArea', INTEGER } }
Box
instances.
Box
インスタンスの面積の合計である84という単一の結果を返します。sqlGroupProjection
method.
sqlGroupProjection
メソッドでグループ化されたプロジェクションをサポートしています。def results = c.list { projections { sqlGroupProjection 'width, sum(height) as combinedHeightsForThisWidth', 'width', ['width', 'combinedHeightsForThisWidth'], [INTEGER, INTEGER] } }
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
インスタンスのリストです。width
によってグループ化した上でheights
を合計した値をプロジェクションしています。
これは以下のような結果を返します:[[2, 24], [4, 9]]
width
の値、次の値はwidth
によってグループ化した上でheight
を合計した値となります。Using SQL Restrictions
SQL Restrictionsの使用
def c = Person.createCriteria()def peopleWithShortFirstNames = c.list { sqlRestriction "char_length(first_name) <= 4" }
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. Thefirst_name
attribute referenced in the example refers to the persistence model, not the object model like in HQL queries. ThePerson
property namedfirstName
is mapped to thefirst_name
column in the database and you must refer to that in thesqlRestriction
string.Also note that the SQL used here is not necessarily portable across databases.
パラメータがSQLであることに注意してください。 上記の例で参照しているfirst_name
属性はHQLクエリのようにオブジェクトモデルではなく、永続化モデルを示します。Person
のfirstName
プロパティはデータベース内のfirst_name
列にマッピングされており、sqlRestriction
文字列内ではfirst_name
を指定する必要があります。また、ここで使われるSQLは必ずしもデータベース間で移植可能ではありません。
Using Scrollable Results
スクロール可能な検索結果の使用
scroll
メソッドを呼び出すことで、HibernateのScrollableResults機能を使用できます:def results = crit.scroll { maxResults(10) } 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')
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上の似た名前のメソッドと同じような意味になります。
Setting properties in the Criteria instance
クライテリアインスタンス内でのプロパティの設定
setMaxResults
and setFirstResult
on the Criteria instance:
setMaxResults
とsetFirstResult
を呼んでいます。import org.hibernate.FetchMode as FM … def results = c.list { maxResults(10) firstResult(50) fetchMode("aRelationship", FM.JOIN) }
Querying with Eager Fetching
Eagerフェッチによるクエリ
def criteria = Task.createCriteria()
def tasks = criteria.list{
eq "assignee.id", task.assignee.id
join 'assignee'
join 'project'
order 'priority', 'asc'
}
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 }
flights
association, you will get reliable results - even with the maxResults
option.
flights
関連を取得するために2次クエリを発行しますが、maxResults
オプションを使いさえすれば、正しい結果が得られます。fetchMode
andjoin
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.
FetchMode
とjoin
はそのクエリ全体に対する設定のため、トップレベルでのみ指定できます。 つまり、プロジェクションや関連のブロック内では使用できません。
def results = Airport.withCriteria { eq "region", "EMEA" flights { like "number", "BA%" } }
flights
collection would be loaded eagerly via a join even though the fetch mode has not been explicitly set.
flights
コレクションはJOINによってEagerフェッチされます。Method Reference
メソッドの参照
c { … }
c.list { … }
Method | Description |
---|---|
list | This is the default method. It returns all matching rows. |
get | Returns 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. |
scroll | Returns a scrollable result set. |
listDistinct | If 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. |
count | Returns the number of matching rows. |
メソッド | 概要 |
---|---|
list | これがデフォルトのメソッドです。条件に一致するすべての行を返します。 |
get | 1つのユニークな結果セット、つまり、1行だけを返します。クライテリアは1行だけを検索するように書かれていなければなりません。このメソッドが最初の行だけに限定して返すと勘違いしないようにしてください。 |
scroll | スクロール可能な結果セットを返します。 |
listDistinct | サブクエリや関連を使うと、結果セット中に同じ行が複数回現れる可能性がありますが、このメソッドは重複したエンティティを取り除いたリストを返します。CriteriaSpecificationクラスのDISTINCT_ROOT_ENTITY を使用するのと同じです。 |
count | 一致する行の数を返します。 |
Combining Criteria
クライテリアの結合
def emeaCriteria = { eq "region", "EMEA" }def results = Airport.withCriteria { emeaCriteria.delegate = delegate emeaCriteria() flights { like "number", "BA%" } }
Airport
).
A more flexible approach is to use Detached Criteria, as described in the following section.
Airport
)に対するものでなければなりません。
より柔軟なアプローチとして、この後のセクションで説明するDetachedクライテリアの使用があります。
6.4.4 Detachedクライテリア
Building Detached Criteria Queries
Detachedクライテリアクエリを構築する
grails.gorm.DetachedCriteria
class which accepts a domain class as the only argument to its constructor:
grails.gorm.DetachedCriteria
クラスです。
このクラスはコンストラクタの引数としてドメインクラスを受け取ります:import grails.gorm.* … def criteria = new DetachedCriteria(Person)
build
method:
build
メソッドを使います:def criteria = new DetachedCriteria(Person).build {
eq 'lastName', 'Simpson'
}
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
Detachedクライテリアクエリの実行する
Method | Description |
---|---|
list | List all matching entities |
get | Return a single matching result |
count | Count all matching records |
exists | Return true if any matching records exist |
deleteAll | Delete all matching records |
updateAll(Map) | Update all matching records with the given properties |
メソッド | 説明 |
---|---|
list | 条件に一致するすべてのエンティティのリストを返す |
get | 条件に一致する単一の結果を返す |
count | 条件に一致するすべての行数を返す |
exists | もし条件に一致する行があればtrue を返す |
deleteAll | 条件に一致するすべての列を削除する |
updateAll(Map) | 条件に一致するすべての列を与えられたプロパティ値で更新する |
firstName
property:
firstName
でソートされた行から条件に一致する最初の4件のリストになります:def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } def results = criteria.list(max:4, sort:"firstName")
list
メソッドへ追加のクライテリアを渡すこともできます:def results = criteria.list(max:4, sort:"firstName") {
gt 'age', 30
}
get
or find
methods (which are synonyms):
get
メソッドまたはfind
メソッド(どちらでも同じ)を使います:Person p = criteria.find() // or criteria.get()
DetachedCriteria
class itself also implements the Iterable
interface which means that it can be treated like a list:
DetachedCriteria
クラス自身がIterable
インタフェースを実装しているため、リストのように扱うこともできます:def criteria = new DetachedCriteria(Person).build {
eq 'lastName', 'Simpson'
}
criteria.each {
println it.firstName
}
each
method is called. The same applies to all other Groovy collection iteration methods.
each
メソッドが呼ばれたときにだけ1度実行されます。
これは、Groovyがコレクションで提供している他のイテレーションメソッドでも同じです。DetachedCriteria
just like on domain classes. For example:
DetachedCriteria
上でダイナミックファインダを実行することもできます:def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } def bart = criteria.findByFirstName("Bart")
Using Detached Criteria for Subqueries
サブクエリにDetachedクライテリアを使う
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" }
Person
) and hence the query can be shortened to:
def results = Person.withCriteria { gt "age", { projections { avg "age" } } order "firstName" }
gtAll
query can be used:
getAll
クエリを使います:def results = Person.withCriteria { gtAll "age", { projections { property "age" } between 'age', 18, 65 }order "firstName" }
Method | Description |
---|---|
gtAll | greater than all subquery results |
geAll | greater than or equal to all subquery results |
ltAll | less than all subquery results |
leAll | less than or equal to all subquery results |
eqAll | equal to all subquery results |
neAll | not equal to all subquery results |
Method | Description |
---|---|
gtAll | サブクエリの結果すべてより大きい |
geAll | サブクエリの結果すべてより大きい、または等しい |
ltAll | サブクエリの結果すべてより小さい |
leAll | サブクエリの結果すべてより大きい、または等しい |
eqAll | サブクエリの結果すべてと等しい |
neAll | サブクエリの結果すべてと等しくない |
Batch Operations with Detached Criteria
Detachedクライテリアによるバッチ処理
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.
バッチ処理の1つの制限として、結合クエリ(関連のクエリ)はDetachedCriteria
インスタンスで使用できないことに注意してください。
deleteAll
method:
deleteAll
メソッドを使います:def criteria = new DetachedCriteria(Person).build { eq 'lastName', 'Simpson' } int total = criteria.deleteAll()
6.4.5 Hibernateクエリー言語 (HQL)
def results =
Book.findAll("from Book as b where b.title like 'Lord of the%'")
位置パラメータと名前付きパラメータ
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 = ?", [author])
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])
複数行のクエリ
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.
トリプルクォートを使ったGroovyの複数行文字列は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の機能
6.5.1 イベントと自動タイムスタンプ
beforeInsert
- Executed before an object is initially persisted to the databasebeforeUpdate
- Executed before an object is updatedbeforeDelete
- Executed before an object is deletedbeforeValidate
- Executed before an object is validatedafterInsert
- Executed after an object is persisted to the databaseafterUpdate
- Executed after an object has been updatedafterDelete
- Executed after an object has been deletedonLoad
- Executed when an object is loaded from the database
beforeInsert
- データベースにオブジェクトが新規保存される前に実行されるbeforeUpdate
- オブジェクトが更新される前に実行されるbeforeDelete
- オブジェクトが削除される前に実行されるbeforeValidate
- オブジェクトがバリデートされる前に実行されるafterInsert
- データベースにオブジェクトが新規保存された後に実行されるafterUpdate
- オブジェクトが更新された後に実行されるafterDelete
- オブジェクトが削除された後に実行されるonLoad
- オブジェクトがデータベースからロードされたときに実行される
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を引き起こしてしまいます。
イベントの種類
beforeInsertイベント
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() } } }
beforeUpdateイベント
class Person {def securityService
String firstName String lastName String lastUpdatedBy
static constraints = { lastUpdatedBy nullable: true }
def beforeUpdate() { lastUpdatedBy = securityService.currentAuthenticatedUsername() } }
beforeDeleteイベント
class Person { String namedef beforeDelete() { ActivityTrace.withNewSession { new ActivityTrace(eventName: "Person Deleted", data: name).save() } } }
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()
のような永続化メソッドによってオブジェクトを保存することはできません。withNewSession
method lets you share the same transactional JDBC connection even though you're using a different underlying Session
.withNewSession
メソッドを使うと、Session
そのものは異なりますが、同一トランザクション内のJDBCコネクションを共有できます。beforeValidateイベント
class Person { String namestatic constraints = { name size: 5..45 }
def beforeValidate() { name = name?.trim() } }
beforeValidate
method is run before any validators are run.beforeValidate
メソッドが実行されます。Validation may run more often than you think. It is triggered by theバリデーションはあなたが考えるよりも多くの頻度で実行される可能性があります。 あなたの予想通りvalidate()
andsave()
methods as you'd expect, but it is also typically triggered just before the view is rendered as well. So when writingbeforeValidate()
implementations, make sure that they can handle being called multiple times with the same property values.validate()
とsave()
メソッドによって実行されますが、ビューがレンダリングされる直前にもよく実行されます。 このため、beforeValidate
の実装を書くときには、同じプロパティ値で複数回呼ばれても処理できるように気をつけてください。
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.List
パラメータを受け取る、オーバロードされたバージョンのbeforeValidate
をサポートします。
このbeforeValidate
は、validate
メソッドが実行されてプロパティ名のList
を引数として渡されたときに呼ばれます。class Person { String name String town Integer agestatic 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 whenvalidate
is triggered indirectly because of a call to thesave
method that thevalidate
method is being invoked with no arguments, not aList
that includes all of the property names.save
メソッドの呼出によってvalidate
が間接的に実行されるとき、validate
メソッドは、すべてのプロパティ名を含むList
を引数として受け取るのではなく、引数なしで実行されていることに注意してください。
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は、List
がvalidate
に渡されればList
バージョンを選ぼうとしますが、もしList
バージョンが存在しなければ、引数なしバージョンにフォールバックします。
同様に、GORMはvalidate
に引数が渡されなければ引数なしバージョンを選ぼうとしますが、もし引数なしバージョンが存在しなければ、List
バージョンにフォールバックします。
そのような場合、null
がbeforeValidate
に渡されます。onLoad/beforeLoadイベント
class Person { String name Date dateCreated Date lastUpdateddef onLoad() { log.debug "Loading ${id}" } }
beforeLoad()
is effectively a synonym for onLoad()
, so only declare one or the other.beforeLoad()
は実質的にonLoad()
の別名なので、どちらか一方だけを宣言すれば良いです。afterLoadイベント
class Person { String name Date dateCreated Date lastUpdateddef afterLoad() { name = "I'm loaded" } }
カスタムイベントリスナ
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:AbstractPersistenceEventListener
のサブクラスと、そのonPersistenceEvent
とsupportsEventType
メソッドの実装が必要です。
また、リスナにデータストアへの参照を渡さなければなりません。
もっとも単純な実装を以下に示します:public MyPersistenceListener(final Datastore datastore) { super(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 }
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()
メソッドも提供されます。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)
}
}
def doWithApplicationContext = { applicationContext ->
application.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
applicationContext.addApplicationListener new MyPersistenceListener(datastore)
}
}
Hibernateイベント
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イベントに対して登録するリスナを指定します。AuditEventListener
which implements PostInsertEventListener
, PostUpdateEventListener
, and PostDeleteEventListener
using the following in an application:PostInsertEventListener
とPostUpdateEventListener
とPostDeleteEventListener
を実装したAuditEventListener
クラスを登録できます:beans = {auditListener(AuditEventListener)
hibernateEventListeners(HibernateEventListeners) { listenerMap = ['post-insert': auditListener, 'post-update': auditListener, 'post-delete': auditListener] } }
def doWithSpring = {auditListener(AuditEventListener)
hibernateEventListeners(HibernateEventListeners) { listenerMap = ['post-insert': auditListener, 'post-update': auditListener, 'post-delete': auditListener] } }
自動タイムスタンプ
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
プロパティを定義した場合は、永続化されたインスタンスが変更されるときにその値が自動的に更新されます。class Person { Date dateCreated Date lastUpdated static mapping = { autoTimestamp false } }
If you haveもしnullable: false
constraints on eitherdateCreated
orlastUpdated
, your domain instances will fail validation - probably not what you want. Omit constraints from these properties unless you disable automatic timestamping.dateCreated
やlastUpdated
にnullable: false
を指定すると、おそらくあなたの望んだ動作ではないでしょうが、ドメインインスタンスのバリデーションに失敗します。 自動タイムスタンプを無効化しない場合は、これらのプロパティに制約を与えないでください。
6.5.2 O/Rマッピングのカスタマイズ
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をレガシースキーマにマッピングしたり、キャッシュを設定したりするようなカスタマイズが必要な場合にのみ、この機能が必要となります。
mapping
block defined within your domain class:mapping
ブロックを利用して設定します:class Person { … static mapping = { version false autoTimestamp false } }
grails.gorm.default.mapping = { version false autoTimestamp false }
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
内でこれらのデフォルト設定を上書きすることもできます。
6.5.2.1 テーブル名、カラム名
テーブル名
table
method:table
メソッドを使ってカスタマイズすることができます:class Person {
…
static mapping = {
table 'people'
}
}
people
instead of the default name of person
.person
の代わりにpeople
テーブルに対応付けられます。カラム名
class Person {String firstName
static mapping = { table 'people' firstName column: 'First_Name' } }
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.firstName
はmapping
クロージャ内におけるダイナミックメソッドで、Map型の引数を1つ取ります。
その名前はドメインクラスの永続化フィールドと対応していて、Map引数の値(この例ではちょうど"column"
の値)はこのプロパティとのマッピングに使われます。カラムの型
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 } }
class Address {String number String postCode
static mapping = { postCode type: 'text' } }
postCode
column map to the default large-text type for the database you're using (for example TEXT or CLOB).postCode
カラムを使用中のデータベースの標準ラージ文字列型(例えば、TEXTやCLOB型)に対応付けています。多対1/1対1マッピング
class Person {String firstName Address address
static mapping = { table 'people' firstName column: 'First_Name' address column: 'Person_Address_Id' } }
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
に変更されます。1対多マッピング
Person
and Address
the following code will change the foreign key in the address
table:Person
とAddress
間の単方向1対多関連では、以下のコードでaddress
テーブルに対する外部キーカラム名を変更できます。class Person {String firstName
static hasMany = [addresses: Address]
static mapping = { table 'people' firstName column: 'First_Name' addresses column: 'Person_Address_Id' } }
address
table, but instead some intermediate join table you can use the joinTable
parameter:joinTable
パラメータが使えます。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'] } }
多対多マッピング
class Group {
…
static hasMany = [people: Person]
}
class Person { … static belongsTo = Group static hasMany = [groups: Group] }
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.group_person
という名前の結合テーブルを生成します。
この結合テーブルは、person
とgroup
テーブルを参照するperson_id
とgroup_id
という名前の外部キーを持っています。
このカラム名を変更するには、それぞれのクラスのmapping
内にcolumn
を指定します。class Group { … static mapping = { people column: 'Group_Person_Id' } } class Person { … static mapping = { groups column: 'Group_Group_Id' } }
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' } }
6.5.2.2 キャッシングストラテジ
キャッシング設定
grails-app/conf/DataSource.groovy
file as follows:grails-app/conf/DataSource.groovy
で次のような設定が必要です:hibernate { cache.use_second_level_cache=true cache.use_query_cache=true cache.provider_class='org.hibernate.cache.EhCacheProvider' }
For further reading on caching and in particular Hibernate's second-level cache, refer to the Hibernate documentation on the subject.キャッシングと、特にHibernateの二次キャッシュについてもっと知りたい場合は、Hibernateのドキュメントを参照してください。
インスタンスのキャッシュ
cache
method in your mapping block to enable caching with the default settings:mapping
ブロックの中でcache
メソッドを呼びます:class Person { … static mapping = { table 'people' cache true } }
class Person {
…
static mapping = {
table 'people'
cache usage: 'read-only', include: 'non-lazy'
}
}
関連のキャッシュ
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 }
addresses
collection. You can also use:addresses
コレクション上でのread-writeキャッシュ機構を有効にします。
より細かくカスタマイズするためにcache: 'read-write' // or 'read-only' or 'transactional'
クエリのキャッシュ
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.キャッシュされたクエリの結果のために、前のセクションで示したようにmapping
でキャッシュを有効にしなければなりません。
def people = Person.withCriteria {
like('firstName', 'Fr%')
cache true
}
キャッシュの使い方
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, anonstrict-read-write
cache might be appropriate.transactional
- Thetransactional
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 specifyhibernate.transaction.manager_lookup_class
in thegrails-app/conf/DataSource.groovy
file'shibernate
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
を指定も必要です。
6.5.2.3 継承ストラテジ
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:table-per-hierarchy
継承マッピングを用います。
この場合、データベースレベルでNOT-NULL
制約が適用できないというデメリットがあります。
もしtable-per-subclass
継承を使いたければ、次のように書くことができます:class Payment { Integer amountstatic mapping = { tablePerHierarchy false } }
class CreditCardPayment extends Payment { String cardNumber }
Payment
class specifies that it will not be using table-per-hierarchy
mapping for all child classes.Payment
スーパクラスのマッピングで、すべてのサブクラスに対してtable-per-hierarchy
マッピングを使わないように指定しています。
6.5.2.4 データベース識別子のカスタマイズ
class Person { … static mapping = { table 'people' version false id generator: 'hilo', params: [table: 'hi_value', column: 'next_value', max_lo: 100] } }
For more information on the different Hibernate generators refer to the Hibernate reference documentationHibernateの各種ジェネレータについての情報は、Hibernateリファレンスドキュメントを参照してください。
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:id
フィールドを指定することはありませんが、
他のプロパティと同様にマッピングを変更することもできます:class Person { … static mapping = { table 'people' version false id column: 'person_id' } }
6.5.2.5 複合主キー
import org.apache.commons.lang.builder.HashCodeBuilderclass 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'] } }
firstName
and lastName
properties of the Person class. To retrieve an instance by id you use a prototype of the object itself:Person
クラスのfirstName
とlastName
プロパティを複合主キーにしています。
IDでインスタンスを取得するためには、そのドメインクラスの未保存のインスタンスを検索条件として使用します:def p = Person.get(new Person(firstName: "Fred", lastName: "Flintstone")) println p.firstName
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
インターフェイスの実装とequals
とhashCode
メソッドのオーバライドが必要です。
これによって複合キーのプロパティを同一性の算定に利用できるようになります。
前述の例では、簡便のためHashCodeBuilder
を利用しましたが、もちろん自分で実装しても構いません。class Address { Person person }
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_name
とperson_last_name
という2つのカラムが追加されることになります。
もし、これらのカラムへの対応付けを変更したいのであれば、次のようにできます:class Address { Person person static mapping = { columns { person { column name: "FirstName" column name: "LastName" } } } }
6.5.2.6 データベースインデックス
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' } }
index
attribute; in this example index:'Name_Idx, Address_Index'
will cause an error.index
属性の値にスペースを入れることはできないことに注意してください。
例えば、index:'Name_Idx, Address_Index'
はエラーになります。
6.5.2.7 楽観的ロックとバージョニング
version
property into every class which is in turn mapped to a version
column at the database level.version
カラムにそれぞれ対応付けられているversion
プロパティを全てのドメインクラスに自動的に注入します。version
method:version
カラムを持たないレガシースキーマとの対応付けをしている(または、楽観的ロックを必要としない他の理由がある)ならば、version
メソッドを使ってこの機能を無効化できます。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楽観的ロックを無効化した場合、同時更新に対するサポートがなくなるため、悲観的ロックを使わない限り(データ上書きによる)ユーザのデータ消失リスクに晒されます。
バージョンのカラム型
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:version
プロパティをLong
型にマッピングし、インスタンスが更新されるごとにインクリメントします。
しかし、HibernateはTimetamp
型もサポートしています。例えば:import java.sql.Timestampclass Person {
… Timestamp version
static mapping = { table 'people' } }
Timestamp
instead of a Long
is that you combine the optimistic locking and last-updated semantics into a single column.Long
型の代わりにTimestamp
型を使うメリットの1つは、1つのカラムで楽観的ロックと最終更新日時の意味を兼任できることです。
6.5.2.8 EagerフェッチとLazyフェッチ
Lazyコレクション
- lazy: false
- fetch: 'join'
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
}
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はより高コストなアプローチになってしまう可能性もあります。- batchSize: N
- lazy: false, batchSize: N
Person
:Person
でのマッピングを考えます。class Person {String firstName Pet pet
static mapping = { pet batchSize: 5 } }
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
インスタンスをフェッチします。
batchSize
とlazy: false
オプションを同時に指定したEagerフェッチの場合も同じ挙動になります。
Hibernateユーザガイドのフェッチ戦略とフェッチ戦略入門で、これらのオプションについてもっと情報を得ることができます。
ORM DSLは今のところ「subselect」フェッチ戦略をサポートしていないことに注意してください。Lazy単一終端関連
class Person {
String firstName
}
class Address {String street String postCode
static belongsTo = [person: Person]
static mapping = { person lazy: false } }
Person
instance (through the person
property) whenever an Address
is loaded.Address
がロードされるごとに、(person
プロパティを通して)関連づけられたPerson
インスタンスをロードするようにGORMを設定しています。Lazy単一終端関連とプロキシ
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はデータベースからそのエンティティをロードします。class Pet {
String name
}
class Dog extends Pet {
}
class Person {
String name
Pet pet
}
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
def person = Person.get(1) assert person.pet instanceof Dog assert Pet.list()[0] instanceof Dog
assert Pet.list()[0] instanceof Dog
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.Person
インスタンスをロードしたとき、Hibernateはpet
プロパティ用にプロキシを生成してセッションにアタッチします。
一度その状態になってしまうと、 同一セッション内で クエリやget()
やpet
プロパティを経由してPet
インスタンスを取得するたびに、Hibernateはセッションに登録されているプロキシを返します。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.get()
とfindBy*()
を使ったとき、または、直接関連プロパティにアクセスしたときには、自動的にプロキシをアンラップしてくれます。
これは大部分のケースにおいては、プロキシについて少しも心配する必要がないことを意味します。
しかし、list()
やfindAllBy*()
のようなリストを返すクエリによって取得したオブジェクトに対しては、GORMはそのようなサポートをしてくれません。
しかし、Hibernateがプロキシをセッションにアタッチしていなければ、これらのクエリはプロキシではない本物のインスタンスを返します。このため、先ほどの最後の例はうまく動作したのです。instanceOf
method by GORM:instanceOf
メソッドを使ってこの問題をある程度回避することもできます。def person = Person.get(1) assert Pet.list()[0].instanceOf(Dog)
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]
Dog
properties or methods on the instance without any problems.Dog
プロパティやメソッドにアクセスできます。6.5.2.9 カスケードの振る舞いを変える
cascade
attribute.cascade
属性を使った完全なアクセスを提供しています。cascade
属性のための有効な設定値は以下の通りです:merge
- merges the state of a detached associationsave-update
- cascades only saves and updates to an associationdelete
- cascades only deletes to an associationlock
- useful if a pessimistic lock should be cascaded to its associationsrefresh
- cascades refreshes to an associationevict
- cascades evictions (equivalent todiscard()
in GORM) to associations if setall
- cascade all operations to associationsall-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様々なカスケード方式と推奨される利用方法についてより良く理解するために、Hibernateのドキュメントの連鎖的な永続化のセクションを読むことをお勧めします。
cascade
属性を指定するには、単純に1つまたは(カンマで区切られた)複数の前述の設定値を定義します。class Person {String firstName
static hasMany = [addresses: Address]
static mapping = { addresses cascade: "all-delete-orphan" } }
class Address { String street String postCode }
6.5.2.10 Hibernateのカスタム型
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.embedded
プロパティによるコンポジションが使えることを説明しました。
Hibernateのカスタム型を利用すると同じようなことができます。
カスタム型自体はドメインクラスではなく、普通のJavaやGroovyクラスです。
また、それぞれのカスタム型には対応する「メタ型(meta-type)」クラスがあります。メタ型クラスはorg.hibernate.usertype.UserTypeインタフェースを実装します。class Book {String title String author Rating rating
static mapping = { rating type: RatingUserType } }
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」のような他のカラムの設定を使うこともできます。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 } }
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
type
, cascade
, lazy
, cache
, and joinTable
.type
, cascade
, lazy
, cache
, joinTable
sqlType
attribute: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" } }
6.5.2.11 派生プロパティ
class Product { Float price Float taxRate Float tax }
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
プロパティがprice
とtaxRate
プロパティの値に基づいて算出されているなら、おそらくtax
プロパティを永続化する必要はないでしょう。
派生プロパティの算出に使われるSQLは、ORM DSLで次のように表すことができます:class Product { Float price Float taxRate Float taxstatic mapping = { tax formula: 'PRICE * TAX_RATE' } }
PRICE
and TAX_RATE
instead of price
and taxRate
.price
とtaxRate
ではなく、PRICE
とTAX_RATE
となっているのはそのためです。Product.get(42)
, the SQL that is generated to support that will look something like this:Product.get(42)
のように取得されたとき、生成されるSQLは次のようになります:select 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_ from product product0_ where product0_.id=?
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()
のようなメソッドを追加して、単純にtaxRate
とprice
プロパティの積を返すようにすることで、同じ結果を達成できるようにみえるかもしれません。
しかし、そのようなアプローチでは、tax
プロパティの値に基づいてデータベースを検索する能力を放棄することになります。
派生プロパティを使えばそれが可能です。
たとえば、tax
の値が21.12以上のすべてのProduct
オブジェクトを取得するために、
次のようなクエリを実行できます:Product.findAllByTaxGreaterThan(21.12)
Product.withCriteria { gt 'tax', 21.12f }
select 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_ from product this_ where 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の制約を適用できません。 もし派生プロパティに対して制約が指定されても無視されます。
6.5.2.12 命名規則のカスタマイズ
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.ImprovedNamingStrategy
を使って、キャメルケースからアンダースコア区切りに変換することで、ドメインクラスのクラス名とフィールド名をSQLのテーブル名とカラム名に変換します。
テーブル名やカラム名はmapping
クロージャでクラスごとにカスタマイズできますが、もし一貫した命名規則が存在するのであれば、異なるNamingStrategy
クラスを使うように指定できます。grails-app/conf/DataSource.groovy
in the hibernate
section, e.g.hibernate
セクションのgrails-app/conf/DataSource.groovy
で使われるクラス名を指定します。例えば:dataSource { pooled = true dbCreate = "create-drop" … }hibernate { cache.use_second_level_cache = true … naming_strategy = com.myco.myproj.CustomNamingStrategy }
hibernate { … naming_strategy = 'com.myco.myproj.CustomNamingStrategy' }
hibernate {
…
def strategy = new com.myco.myproj.CustomNamingStrategy()
// configure as needed
naming_strategy = strategy
}
package com.myco.myprojimport 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 デフォルトソート順
def airports = Airport.list(sort:'name')
mapping
でコレクションに対するデフォルトソート順を宣言することもできます。class Airport { … static mapping = { sort "name" } }
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" } }
class Airport { … static hasMany = [flights: Flight]static mapping = { flights sort: 'number', order: 'desc' } }
flights
collection will always be sorted in descending order of flight number.flights
コレクションは常にフライト番号の降順でソートされます。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これらのマッピングはデフォルトの単方向1対多/多対多関連では動作しません。結合テーブルが使われているためです。 より詳しくは、このチケットを参照してください。 それらのソートされたデータを取得するには、SortedSet
or queries with sort parameters to fetch the data you need.SortedSet
やソートパラメータを指定したクエリを使うことを検討してください。
6.6 プログラマチックトランザクション
withTransaction
in a controller methods:コントローラのメソッドでwithTransaction
を利用する例を示します:
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() } } } }
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.RuntimeException
やError
がトランザクション処理中にスローされた場合も、自動的にロールバックされます。
(Groovyはチェック例外のcatchを必須としていないため、チェック例外と非チェック例外の区別が曖昧になりがちですが)チェック例外であるException
の場合にはロールバックされません。withTransaction
method deals with the begin/commit/rollback logic for you within the scope of the block.withTransaction
メソッドは、ブロックのスコープ内で開始/コミット/ロールバックを制御します。6.7 GORMと制約
String name String description
Column | Data Type |
---|---|
name | varchar(255) |
description | varchar(255) |
description
は1000文字まで入力したいかもしれません。
その場合、 もし SQLスクリプトでテーブルを作成しているなら、たぶん次のようにカラムを定義するでしょう。Column | Data Type |
---|---|
description | TEXT |
static constraints = {
description maxSize: 1000
}
文字列型プロパティに影響する制約
maxSize
or the size
constraint is defined, Grails sets the maximum column length based on the constraint value.maxSize
とsize
制約のどちらかが定義されると、Grailsは制約の値に従ってカラムの最大長を設定します。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つの値の最小値を利用するのは、その最小値を超える長さであれば結局バリデーションエラーになるためです。)
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
制約が定義された場合(maxSize
とsize
制約は定義されていないとする)、Grailsは有効な値のリストの中でもっとも長い文字列長を元にカラムの長さをセットします。
例えば、"Java", "Groovy", "C++"を含むリストが与えられた場合、Grailsはカラムの長さを6(すなわち、"Groovy"の文字数)にセットします。
数値型プロパティに影響する制約
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.)max
やmin
, range
制約が定義されると、Grailsは制約の値に基づいた精度(有効桁数)をカラムにセットしようと試みます。
(その試みが成功するかどうかは、Hibernateが裏にあるDBMSとどのように相互作用するかに大きく依存します。)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がそれらの最小精度を利用するのは、その最小精度を超える場合は結局バリデーションエラーになるためです。)
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とどのように相互作用するかに大きく依存します。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
/min
やrange
制約では、最大/最小の数値を定義します。そして、そこからGrailsは精度として利用するための最大桁数を算出します。
指定された制約値がHibernateのデフォルトカラム精度(現在は19)よりも多くの桁数を必要とする場合を除いて、min
制約とmax
制約のどちらかひとつだけを指定しても、スキーマ生成には影響しないことを覚えておいてください。
(なぜなら、例えばmax:100
を指定したとしても、大きな負の数も許容されるため、必要な精度は確定できないからです。)例えば:
someFloatValue max: 1000000, scale: 3
someFloatValue DECIMAL(19, 3) // precision is default
someFloatValue max: 12345678901234567890, scale: 5
someFloatValue DECIMAL(25, 5) // precision = digits in max + scale
someFloatValue max: 100, min: -100000
someFloatValue DECIMAL(8, 2) // precision = digits in min + default scale
7 Webレイヤ
7.1 コントローラ
Controller
in the grails-app/controllers
directory (in a subdirectory if it's in a package).grails-app/controlers
ディレクトリに、クラス名称の最後をController
にしたクラスを作成することで、コントローラを追加できます。(パッケージに入れる場合は、パッケージ名のサブディレクトリに作成します。)7.1.1 コントローラとアクションの理解
コントローラを作成する
grails create-controller book
grails-app/controllers/myapp/BookController.groovy
:grails-app/controllers/myapp/BookController.groovy
にコントローラを生成します。package myappclass BookController {
def index() { } }
BookController
by default maps to the /book URI (relative to your application root).BookController
は、URIが /bookとなります。(アプリケーションのコンテキストルートからの相対パス)Thecreate-controller
andgenerate-controller
commands are just for convenience and you can just as easily create controllers using your favorite text editor or IDEcreate-controller
とgenerate-controller
コマンドは、簡単にコントローラを生成する便利なコマンドですが、IDEやテキストエディタの機能でクラスを作成してもかまいません。
create-controller
とgenerate-controller
コマンドは、簡単にコントローラを生成する便利なコマンドですが、IDEやテキストエディタの機能でクラスを作成してもかまいません。
アクションの作成
class BookController {def list() {
// do controller logic // create model
return model } }
/book/list
URI by default thanks to the property being named list
.list
なので、URIは/book/list
にマップされます。パブリックメソッドをアクションとする
- 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()
- クロージャはフィールドのため複雑だった、スタンダードなプロキシを使用したメソッドのインターセプトが可能。
grails.compile.artefacts.closures.convert
property to true in BuildConfig.groovy
:BuildConfig.groovy
に、 grails.compile.artefacts.closures.convert
を定義します:
grails.compile.artefacts.closures.convert = true
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.
デフォルトアクション
/book
for BookController
. The action that is called when the default URI is requested is dictated by the following rules: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 コントローラとスコープ
使用可能なスコープ
- 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 - 以下を参照
スコープへのアクセス
class BookController { def find() { def findBy = params["findBy"] def appContext = request["foo"] def loggedUser = session["logged_user"] } }
class BookController { def find() { def findBy = params.findBy def appContext = request.foo def loggedUser = session.logged_user } }
フラッシュスコープを使用する
def delete() { def b = Book.get(params.id) if (!b) { flash.message = "User not found for id ${params.id}" redirect(action:list) } … // remaining code }
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.delete
アクションに対してリクエストをすると、リダイレクトされてlist
アクションが実行された際に、flashスコープのmessage
に代入した内容がメッセージ表示等に使用可能になります。このリダイレクトされたlist
アクション(delete
の次のアクション)の処理が終了したら、flash
スコープの内容が削除されます。コントローラのスコープ
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 sessionsingleton
- Only one instance of the controller ever exists (recommended for actions as methods)
prototype
(デフォルト) - リクエスト毎にコントローラが生成されます。(クロージャでアクションを推奨)session
- ユーザのセッションを通して1個のコントローラが生成されます。singleton
- 1個のコントローラのみが存在する状態です。(メソッドでのアクションをお勧めします)
scope
property to your class with one of the valid scope values listed above, for examplestatic scope = "singleton"
Config.groovy
with the grails.controllers.defaultScope
key, for example:Config.groovy
にgrails.controllers.defaultScope
を指定する事で変更できます。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 thanprototype
may also lead to unexpected behaviors if you have controllers provided by installed plugins that expect that the scope isprototype
.
コントローラのスコープは使用状況を考えてお使いください。例えば、シングルトンのコントローラは、_全ての_リクエストで共有されるためプロパティを持つべきではありません。デフォルトで定義されているスコープのprototype
を変更することで、プラグインなどで提供されたコントローラがprotopype
を前提で実装されている場合があるので注意しましょう
7.1.3 モデルとビュー
モデルを返す
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.上記の例はスカッフォルドのビューで使用する例ではありません。スカッフォルドに関しては、スカッフォルドのセクションを参照してください。
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.これはコントローラのスコープがprototype(リクエスト毎にコントローラが生成される)の場合に可能な方法です。他の場合はスレッドセーフではありません。
books
and authors
properties will be available in the view.book
とauthors
がビューで参照できます。import org.springframework.web.servlet.ModelAndViewdef index() { // get some books just for the index page, perhaps your favorites def favoriteBooks = ...
// forward to the list view to show them return new ModelAndView("/book/list", [ bookList : favoriteBooks ]) }
attributes
application
ビューの選択Selecting the View
grails-app/views/book/show.gsp
for this show
action:grails-app/views/book/show.gsp
をビューとして使用します。class BookController { def show() { [book: Book.get(params.id)] } }
def show() {
def map = [book: Book.get(params.id)]
render(view: "display", model: map)
}
grails-app/views/book/display.gsp
. Notice that Grails automatically qualifies the view location with the book
directory of the grails-app/views
directory. This is convenient, but to access shared views you need instead you can use an absolute path instead of a relative one:grails-app/views/book/display.gsp
の描写を試みます。注目する場所はGrailsは自動的にコントローラがbook
であれば、grails-app/views
ディレクトリのbook
ディレクトリを、指定しなくても取得する所です。これは便利なのですが、ビューを共有する場合は、パスを指定する必要があります。def show() {
def map = [book: Book.get(params.id)]
render(view: "/shared/display", model: map)
}
grails-app/views/shared/display.gsp
.grails-app/views/shared/display.gsp
の描写を試みます。レスポンスの描写
render
method can be used:render
メソッドを使うと簡単にできます。render "Hello World!"
// マークアップを返す
render {
for (b in books) {
div(id: b.id, b.title)
}
}
// 指定したビューを描写 render(view: 'show')
// コレクションの中身をそれぞれ指定したテンプレートを適応して描写 render(template: 'book_template', collection: Book.list())
// 文字列を指定したエンコーディングとコンテントタイプで描写 render(text: "<xml>some xml</xml>", contentType: "text/xml", encoding: "UTF-8")
MarkupBuilder
to generate HTML for use with the render
method be careful of naming clashes between HTML elements and Grails tags, for example:render
メソッドでGroovyのMarkupBuilder
を使用してHTMLを生成する場合は、HTMLエレメント名とGrailsタグとの名称衝突を気をつけましょう。(Grailsのタグはアクション内部でメソッドとして使用できるため)import groovy.xml.MarkupBuilder … def login() { def writer = new StringWriter() def builder = new MarkupBuilder(writer) builder.html { head { title 'Log in' } body { h1 'Hello' form { } } }def html = writer.toString() render html }
MarkupBuilder
). To correctly output a <form>
element, use the following:<form>
タグを正常に生成するには、以下のようにbuilder.form
とします。def login() { // … body { h1 'Hello' builder.form { } } // … }
7.1.4 リダイレクトとチェイン
リダイレクトRedirects
class OverviewController {def login() {}
def find() { if (!session.user) redirect(action: 'login') return } … } }
sendRedirect
メソッドを使用しています。redirect
method expects one of:redirect
メソッドでは以下のいずれかのように使用します:// Call the login action within the same class redirect(action: login)
- アクション名称でのしていと、別のコントローラのアクションの場合はコントローラの指定:
// Also redirects to the index action in the home controller redirect(controller: 'home', action: 'index')
- アプリケーションコンテキストパス内のリソースのURI:
// Redirect to an explicit URI
redirect(uri: "/login.html")
- URLを全指定:
// Redirect to a URL
redirect(url: "http://grails.org")
params
argument of the method:redirect(action: 'myaction', params: [myparam: "myvalue"])
params
object is a Map, you can use it to pass the current request parameters from one action to the next:params
オブジェクトはMapなので、以下のように、そのまま全てのリクエストパラメータを次のアクションに渡すことができます:redirect(action: "next", params: params)
redirect(controller: "test", action: "show", fragment: "profile")
チェイニング Chaining
first
action in this action:first
を呼び出します:class ExampleChainController {def first() { chain(action: second, model: [one: 1]) }
def second () { chain(action: third, model: [two: 2]) }
def third() { [three: 3]) } }
[one: 1, two: 2, three: 3]
chainModel
map. This dynamic property only exists in actions following the call to the chain
method:class ChainController {def nextInChain() { def model = chainModel.myModel … } }
redirect
method you can also pass parameters to the chain
method:redirect
メソッドと同じように、chain
メソッドにパラメータを渡すこともできます:chain(action: "action1", model: [one: 1], params: [myparam: "param1"])
7.1.5 コントローラ・インターセプター
If your interceptor is likely to apply to more than one controller, you are almost certainly better off writing a Filter. Filters can be applied to multiple controllers or URIs without the need to change the logic of each controller複数のコントローラにインターセプターを反映させたい場合は、Filterを使用することをお勧めします。Filterは多数のコントローラまたはURIに、ロジックを追加すること無く反映できます。
ビフォア・インターセプションBefore Interception
beforeInterceptor
intercepts processing before the action is executed. If it returns false
then the intercepted action will not be executed. The interceptor can be defined for all actions in a controller as follows:beforeInterceptor
は、アクションが実行される前に処理の追加を行うことができます。beforeInterceptor
で、false
を返すとアクションは実行されません。コントローラ内の全てのアクションにインターセプターを定義するには以下のようにします。def beforeInterceptor = {
println "Tracing action ${actionUri}"
}
def beforeInterceptor = [action: this.&auth, except: 'login']// defined with private scope, so it's not considered an action private auth() { if (!session.user) { redirect(action: 'login') return false } }
def login() { // display login page }
auth
. A private method is used so that it is not exposed as an action to the outside world. The beforeInterceptor
then defines an interceptor that is used on all actions except the login action and it executes the auth
method. The auth
method is referenced using Groovy's method pointer syntax. Within the method it detects whether there is a user in the session, and if not it redirects to the login
action and returns false
, causing the intercepted action to not be processed.auth
メソッドを定義します。外部にアクションとして認識されないようにprivate
メソッドにします。
今回は、アクション名がlogin
以外の全てのアクションで実行されるように、実行するメソッドをaction:に指定し、除外するアクション'login'を except:に指定して、beforeInterceptor
を定義します。auth
メソッドはGroovyのメソッドポインターシンタックスで指定します。これで、auth
の処理によって、sessionにuser変数が見つからなかった場合は'login'アクションへリダイレクトしてfalse
を返しアクションを実行しないインターセプターが行えます。
アフター・インターセプション After Interception
afterInterceptor
property to define an interceptor that is executed after an action:afterInterceptor
は、アクションが実行される後に処理の追加を行うことができます:def afterInterceptor = { model ->
println "Tracing action ${actionUri}"
}
def afterInterceptor = { model, modelAndView -> println "Current view is ${modelAndView.viewName}" if (model.someVar) modelAndView.viewName = "/mycontroller/someotherview" println "View is now ${modelAndView.viewName}" }
modelAndView
may be null
if the action being intercepted called redirect
or render
.redirect
やrender
を呼び出している場合は、modelANdView
はnull
になります。インターセプションの条件指定 Interception Conditions
def beforeInterceptor = [action: this.&auth, except: 'login']
def beforeInterceptor = [action: this.&auth, except: ['login', 'register']]
def beforeInterceptor = [action: this.&auth, only: ['secure']]
7.1.6 データバインディング
マップを用いたバインディング
// grails-app/domain/Person.groovy class Person { String firstName String lastName Integer age }
def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63]def person = new Person(bindingMap)
assert person.firstName == 'Peter' assert person.lastNaem == 'Gabriel' assert person.age == 63
properties
property of the domain class:properties
プロパティにマップを代入できます。def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63]def person = Person.get(someId) person.properties = bindingMap
assert person.firstName == 'Peter' assert person.lastNaem == 'Gabriel' assert person.age == 63
class Person { String firstName String lastName Integer age Address homeAddress }class Address { String county String country }
def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63, homeAddress: [county: 'Surrey', country: 'England'] ]def person = new Person(bindingMap)
assert person.firstName == 'Peter' assert person.lastNaem == 'Gabriel' assert person.age == 63 assert person.homeAddress.county == 'Surrey' assert person.homeAddress.country == 'England'
コレクションとマップへのバインディング
List
of objects in a domain class:List
への格納の単純な例を示します。class Band { String name static hasMany = [albums: Album] List albums }class Album { String title Integer numberOfTracks }
def bindingMap = [name: 'Genesis', 'albums[0]': [title: 'Foxtrot', numberOfTracks: 6], 'albums[1]': [title: 'Nursery Cryme', numberOfTracks: 7]]def band = new Band(bindingMap)
assert band.name == 'Genesis' assert band.albums.size() == 2 assert band.albums[0].title == 'Foxtrot' assert band.albums[0].numberOfTracks == 6 assert band.albums[1].title == 'Nursery Cryme' assert band.albums[1].numberOfTracks == 7
albums
were an array instead of a List
.albums
がList
の代わりに配列だったとしても同様に動作します。Set
the structure of the Map
being bound to the Set
is the same as that of a Map
being bound to a List
but since a Set
is unordered, the indexes don't necessarily correspond to the order of elements in the Set
. In the code example above, if albums
were a Set
instead of a List
, the bindingMap
could look exactly the same but 'Foxtrot' might be the first album in the Set
or it might be the second. When updating existing elements in a Set
the Map
being assigned to the Set
must have id
elements in it which represent the element in the Set
being updated, as in the following example:Set
へとバインディングするとき、Set
にバインドされたMap
の構造はList
にバインドされたMap
と同じですが、Set
は順序を保持しないため、添字は必ずしもSet
内の要素の順序と一致しないことに注意してください。
上記のサンプルコードでalbums
がList
の代わりにSet
だったとしたら、bindingMap
は一見まったく同じに見えるかもしれませんが、「Foxtrot」はSet
内の最初のアルバムかもしれませんし、2番目であるかもしれません。
以下の例のように、Set
内の既存の要素を更新するとき、Set
に代入するMap
は更新されようとしているSet
内の要素を表すid
要素を持っていなければなりません:/* * The value of the indexes 0 and 1 in albums[0] and albums[1] are arbitrary * values that can be anything as long as they are unique within the Map. * They do not correspond to the order of elements in albums because albums * is a Set. */ def bindingMap = ['albums[0]': [id: 9, title: 'The Lamb Lies Down On Broadway'] 'albums[1]': [id: 4, title: 'Selling England By The Pound']]def band = Band.get(someBandId)
/* * This will find the Album in albums that has an id of 9 and will set its title * to 'The Lamb Lies Down On Broadway' and will find the Album in albums that has * an id of 4 and set its title to 'Selling England By The Pound'. In both * cases if the Album cannot be found in albums then the album will be retrieved * from the database by id, the Album will be added to albums and will be updated * with the values described above. If a Album with the specified id cannot be * found in the database, then a binding error will be created and associated * with the band object. More on binding errors later. */ band.properties = bindingMap
Map
the structure of the binding Map
is the same as the structore of a Map
used for binding to a List
or a Set
and the index inside of square brackets corresponds to the key in the Map
being bound to. See the following code:Map
へとバインディングするとき、バインド元のMap
の構造はList
やSet
へのバインディングに使われるMap
と同じです。
角括弧内の添字はバインド先のMap
内のキーとなります。
以下のコードを見てください:class Album { String title static hasMany = [players: Player] Map players }class Player { String name }
def bindingMap = [title: 'The Lamb Lies Down On Broadway', 'players[guitar]': [name: 'Steve Hacket'], 'players[vocals]': [name: 'Peter Gabriel'] 'players[keyboards]': [name: 'Tony Banks']]def album = new Album(bindingMap)
assert album.title == 'The Lamb Lies Down On Broadway' assert album.players.size() == 3 assert album.players.guitar == 'Steve Hacket' assert album.players.vocals == 'Peter Gabriel' assert album.players.keyboards == 'Tony Banks'
Map
, if the key specified in the binding Map
does not exist in the Map
being bound to then a new value will be created and added to the Map
with the specified key as in the following example:Map
を更新するときに、バインド元のMap
内で指定されたキーがバインド先のMap
内に存在しない場合、新しい値が生成されて指定されたキーでバインド先のMap
に追加されます:def bindingMap = [title: 'The Lamb Lies Down On Broadway', 'players[guitar]': [name: 'Steve Hacket'], 'players[vocals]': [name: 'Peter Gabriel'] 'players[keyboards]': [name: 'Tony Banks']]def album = new Album(bindingMap)
assert album.title == 'The Lamb Lies Down On Broadway' assert album.players.size() == 3 assert album.players.guitar == 'Steve Hacket' assert album.players.vocals == 'Peter Gabriel' assert album.players.keyboards == 'Tony Banks'
def updatedBindingMap = ['players[drums]': [name: 'Phil Collins'], 'players[keyboards]': [name: 'Anthony George Banks']]
album.properties = updatedBindingMap
assert album.title == 'The Lamb Lies Down On Broadway' assert album.players.size() == 4 assert album.players.guitar == 'Steve Hacket' assert album.players.vocals == 'Peter Gabriel' assert album.players.keyboards == 'Anthony George Banks' assert album.players.drums == 'Phil Collins'
モデルにリクエストデータをバインドする
person.homeAddress.country
and person.homeAddress.city
with values 'USA' and 'St. Louis' respectively, params
would include entries like these:person.homeAddress.country
とperson.homeAddress.city
という名前のリクエストパラメータを持っているリクエストの場合、params
のエントリは以下のようになります:[person: [homeAddress: [country: 'USA', city: 'St. Louis']]]
def save() {
def b = new Book(params)
b.save()
}
new Book(params)
. By passing the params object to the domain class constructor Grails automatically recognizes that you are trying to bind from request parameters. So if we had an incoming request like:new Book(params)
の部分でデータバインディングが実行されます。paramsオブジェクトをドメインクラスのコンストラクタに渡すことで、Grailsが自動にリクエストパラメータを認識してバインドします。例えば、以下のようなリクエストを受信したとします。/book/save?title=The%20Stand&author=Stephen%20King
title
and author
request parameters would automatically be set on the domain class. You can use the properties property to perform data binding onto an existing instance:title
とauthor
が、自動的にドメインクラスへセットされます。もう1つの方法として、既存のドメインクラスインスタンスへデータバインディングするために、propertiesプロパティを利用することができます。def save() { def b = Book.get(params.id) b.properties = params b.save() }
grails.databinding.trimStrings
property to false in grails-app/conf/Config.groovy
.grails-app/conf/Config.groovy
のgrails.databinding.trimStrings
プロパティにfalseをセットしてください。// the default value is true grails.databinding.trimStrings = false// ...
grails.databinding.convertEmptyStringsToNull
property to false in grials-app/conf/Config.groovy
.grails-app/conf/Config.groovy
のgrails.databinding.convertEmptyStringsToNull
プロパティにfalseをセットしてください。// the default value is true grails.databinding.convertEmptyStringsToNull = false// ...
trimStrings
is true
and convertEmptyStringsToNull
is true
, not only will empty Strings be converted to null but also blank Strings. A blank String is any String such that the trim()
method returns an empty String.trimStrings
がtrue
でconvertEmptyStringsToNull
がtrue
のとき、イベントの順番としては、文字列がトリムされた後にnull変換が実行されます。つまり、空文字がnullに変換されるだけでなく、空白文字列もnullに変換されることになります。
ここで、空白文字列とはtrim()
メソッドが空文字を返す文字列のことです。These forms of data binding in Grails are very convenient, but also indiscriminate. In other words, they will bind all non-transient, typed instance properties of the target object, including ones that you may not want bound. Just because the form in your UI doesn't submit all the properties, an attacker can still send malign data via a raw HTTP request. Fortunately, Grails also makes it easy to protect against such attacks - see the section titled "Data Binding and Security concerns" for more information.Grailsでのこのようなデータバインディングは大変便利ですが、同時に無差別的でもあります。 言い換えると、バインドしたくないものまで含めて、対象オブジェクトの「すべて」の非transientな型付けされたインスタンスプロパティをバインドしてしまいます。 単にUI上のフォームがすべてのプロパティをサブミットするわけではないだけであって、今もなお攻撃者は生のHTTPリクエストを使って悪意あるデータを送信することができます。 幸い、Grailsではそのような攻撃に対して防御するのも簡単です。 詳しくは、「データバインディングとセキュリティ考慮」のセクションを参照してください。
単一終端関連のデータバインディング
one-to-one
or many-to-one
association you can use Grails' data binding capability to update these relationships too. For example if you have an incoming request such as:/book/save?author.id=20
.id
suffix on the request parameter and look up the Author
instance for the given id when doing data binding such as:.id
接尾辞を自動認識して、与えられたidで該当するAuthor
インスタンスを検索してデータバインディングを行いますdef b = new Book(params)
null
by passing the literal String
"null". For example:null
をセットすることができます/book/save?author.id=null
複数終端関連のデータバインディング
Set
based association (the default for a hasMany
) then the simplest way to populate an association is to send a list of identifiers. For example consider the usage of <g:select>
below:Set
ベースの関連(hasMany
でのデフォルト)で、簡単に関連を設定するには、idのリストを送る方法が有ります。以下の例は<g:select>
を使用した方法です:<g:select name="books"
from="${Book.list()}"
size="5" multiple="yes" optionKey="id"
value="${author?.books}" />
books
association.books
の関連を設定します。<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" />
Set
based association it is critical that you render the mark-up in the same order that you plan to do the update in. This is because a Set
has no concept of order, so although we're referring to books0
and books1
it is not guaranteed that the order of the association will be correct on the server side unless you apply some explicit sorting yourself.Set
ベースの関連では、マークアップ(HTML)が描写された順序とは同じ順序で更新されない危険性あります。 これはSet
には順序という概念がなく、books[0]
やbooks[1]
と指定したとしても、サーバサイドでの関連のソートを明快に指定しない限り、順序が保証されないことになるからです。List
based associations, since a List
has a defined order and an index you can refer to. This is also true of Map
based associations.List
ベースの関連の場合は、List
の順序とインデックスを指定することができるので問題ありません。Map
ベースの関連も同じことがいえます。<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" /> <g:textField name="books[2].title" value="Red Madder" />
<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" /> <g:textField name="books[5].title" value="Red Madder" />
List
using the same .id
syntax as you would use with a single-ended association. For example:List
関連でバインドするには、単一終端関連と同じように.id
シンタックスを使用します。例として:<g:select name="books[0].id" from="${bookList}" value="${author?.books[0]?.id}" /><g:select name="books[1].id" from="${bookList}" value="${author?.books[1]?.id}" />
<g:select name="books[2].id" from="${bookList}" value="${author?.books[2]?.id}" />
books List
to be selected separately.books List
の特定の場所にエントリを可能にします。<g:select name="books[0].id"
from="${Book.list()}"
value="${author?.books[0]?.id}"
noSelection="['null': '']"/>
books0
if the empty option is chosen.book[0]
の関連を削除します。Map
property works the same way except that the list index in the parameter name is replaced by the map key:Map
のプロパティも同じ方法で動作します:<g:select name="images[cover].id"
from="${Image.list()}"
value="${book?.images[cover]?.id}"
noSelection="['null': '']"/>
Map
property images
under a key of "cover"
.grails.databinding.autoGrowCollectionLimit
property in Config.groovy
.Config.groovy
のgrails.databinding.autoGrowCollectionLimit
プロパティに値を代入すれば変更できます。// grails-app/conf/Config.groovy// the default value is 256 grails.databinding.autoGrowCollectionLimit = 128
// ...
複数ドメインクラスでのデータバインディング
/book/save?book.title=The%20Stand&author.name=Stephen%20King
author.
or book.
which is used to isolate which parameters belong to which type. Grails' params
object is like a multi-dimensional hash and you can index into it to isolate only a subset of the parameters to bind.author.
またbook.
という接頭辞が付いていて、どちらの型(ドメインクラス)に属するかを区別しています。Grailsのparams
オブジェクトは多次元ハッシュのようになっており、それぞれバインドするためのパラメータサブセットとして区別されて索引されます。def b = new Book(params.book)
book.title
parameter to isolate only parameters below this level to bind. We could do the same with an Author
domain class:book.title
パラメータだけが区別されてバインドされます。ドメインクラスAuthor
も同じように指定します。def a = new Author(params.author)
データバインディングとアクション引数
class AccountingController {// accountNumber will be initialized with the value of params.accountNumber // accountType will be initialized with params.accountType def displayInvoice(String accountNumber, int accountType) { // … } }
params.accountType
request parameter has to be converted to an int
. If type conversion fails for any reason, the argument will have its default value per normal Java behavior (null for type wrapper references, false for booleans and zero for numbers) and a corresponding error will be added to the errors
property of the defining controller.params.accountType
リクエストパラメータはint
型に変換する必要があります。
もし型変換が何らかの理由により失敗した場合は、引数はJava標準的な挙動によるデフォルト値(ラッパー型はnull、boolean型はfalse、数値型は0)をとります。
そして、対応するエラーが対象コントローラのerrors
プロパティに追加されます。/accounting/displayInvoice?accountNumber=B59786&accountType=bogusValue
errors.hasErrors()
will be true, the controller's errors.errorCount
will be equal to 1 and the controller's errors.getFieldError('accountType')
will contain the corresponding error.
"bogusValue"はint型に変換できないため、accountType
は0になります。そして、コントローラのerrors.hasErrors()
はtrueに、errors.errorCount
は1になり、errors.getFieldError('accountType')
には対応するエラーが保持されます。@grails.web.RequestParameter
annotation may be applied to an argument to express the name of the request parameter which should be bound to that argument:@grails.web.RequestParameter
アノテーションを引数に付与することができます。import grails.web.RequestParameterclass AccountingController {
// mainAccountNumber will be initialized with the value of params.accountNumber // accountType will be initialized with params.accountType def displayInvoice(@RequestParameter('accountNumber') String mainAccountNumber, int accountType) { // … } }
型変換エラーとデータバインディング
class Book { … URL publisherURL }
Book
that uses the java.net.URL
class to represent URLs. Given an incoming request such as:Book
でURLを表すプロパティにjava.net.URL
クラスを使用したとします。次のようなリクエストを受信したとします:/book/save?publisherURL=a-bad-url
a-bad-url
to the publisherURL
property as a type mismatch error occurs. You can check for these like this:a-bad-url
をpublisherURL
にバインドすることはできません。次のようにしてエラーを確認します:def b = new Book(params)if (b.hasErrors()) { println "The value ${b.errors.getFieldError('publisherURL').rejectedValue}" + " is not a valid URL!" }
grails-app/i18n/messages.properties
file to use for the error. You can use a generic error message handler such as:grails-app/i18n/messages.properties
を使用してメッセージを返す事もあると思います。次のような一般的なメッセージハンドラーを使用することもできますtypeMismatch.java.net.URL=The field {0} is not a valid URL
typeMismatch.Book.publisherURL=The publisher URL you specified is not a valid URL
BindUsingアノテーション
Map
which is the data source for the data binding. The value returned from the closure will be bound to the property. The following example would result in the upper case version of the name
value in the source being applied to the name
field during data binding.Map
です。
クロージャが返す値はオブジェクトのプロパティにバインドされます。
以下の例では、データバーディングによってデータソースのname
の値が大文字に変換されたものがname
フィールドに設定されます。import org.grails.databinding.BindUsingclass SomeClass { @BindUsing({ obj, source -> source['name']?.toUpperCase() }) String name }
@BindUsing(SomeClassWhichImplementsBindingHelper) class SomeClass { String someProperty Integer someOtherProperty }
カスタムデータコンバータ
package com.myapp.convertersimport org.grails.databinding.converters.ValueConverter
/** * A custom converter which will convert String of the * form 'city:state' into an Address object. */ class AddressValueConverter implements ValueConverter {
boolean canConvert(value) { value instanceof String }
def convert(value) { def pieces = value.split(':') new com.myapp.Address(city: pieces[0], state: pieces[1]) }
Class<?> getTargetType() { com.myapp.Address } }
ValueConverter
を実装したすべてのビーンは、自動的にデータバインディングプロセスに組み込まれます。// grails-app/conf/spring/resources.groovybeans = {
addressConverter com.myapp.converters.AddressValueConverter
// ...
}
class Person { String firstName Address homeAddress }class Address { String city String state }
def person = new Person() person.properties = [firstName: 'Jeff', homeAddress: "O'Fallon:Missouri"] assert person.firstName == 'Jeff' assert person.homeAddress.city = "O'Fallon" assert person.homeAddress.state = 'Missouri'
データバインディングのためのデータフォーマット
Date
の値にバインドするとき、BindingFormatアノテーションをデータフィールドに付与することで、カスタムデータフォーマットを指定できます。import org.grails.databinding.BindingFormatclass Person { @BindingFormat('MMddyyyy') Date birthDate }
A global setting may be configured in Config.groovy
to define date formats which will be used application wide when binding to Date.
// grails-app/conf/Config.groovygrails.databinding.dateFormats = ['MMddyyyy', 'yyyy-MM-dd HH:mm:ss.S', "yyyy-MM-dd'T'hh:mm:ss'Z'"]
The formats specified in grails.databinding.dateFormats
will be attempted in the order in which they are included in the List. If a property is marked with @BindingFormat, the @BindingFormat will take precedence over the values specified in grails.databinding.dateFormats
.
The default formats that are used are "yyyy-MM-dd HH:mm:ss.S" and "yyyy-MM-dd'T'hh:mm:ss'Z'".
カスタムフォーマットコンバータ
BindingFormat
アノテーションが指定された値の文字列の大文字/小文字を変換するという、ちょっとした文字列のカスタムフォーマッタの例です。package com.myapp.convertersimport org.grails.databinding.converters.FormattedValueConverter
class FormattedStringValueConverter implements FormattedValueConverter { def convert(value, String format) { if('UPPERCASE' == format) { value = value.toUpperCase() } else if('LOWERCASE' == format) { value = value.toLowerCase() } value }
Class getTargetType() { // specifies the type to which this converter may be applied String } }
FormattedValueConverter
を実装したすべてのビーンは、自動的にデータバインディングプロセスに組み込まれます。// grails-app/conf/spring/resources.groovybeans = {
formattedStringConverter com.myapp.converters.FormattedStringValueConverter
// ...
}
BindingFormat
annotation may be applied to String fields to inform the data binder to take advantage of the custom converter.BindingFormat
アノテーションを文字列フィールドに適用できます。import org.grails.databinding.BindingFormatclass Person { @BindingFormat('UPPERCASE') String someUpperCaseString
@BindingFormat('LOWERCASE') String someLowerCaseString
String someOtherString }
Localized Binding Formats
The BindingFormat
annotation supports localized format strings by using the optional code
attribute. If a value is assigned to the code attribute that value will be used as the message code to retrieve the binding format string from the messageSource
bean in the Spring application context and that lookup will be localized.
import org.grails.databinding.BindingFormatclass Person { @BindingFormat(code='date.formats.birthdays') Date birthDate }
# grails-app/conf/i18n/messages.properties date.formats.birthdays=MMddyyyy
# grails-app/conf/i18n/messages_es.properties date.formats.birthdays=ddMMyyyy
Using The Data Binder Directly
There are situations where an application may want to use the data binder directly. For example, to do binding in a Service on some arbitrary object which is not a domain class. The following will not work because the properties
property is read only.
// src/groovy/bindingdemo/Widget.groovy package bindingdemoclass Widget { String name Integer size }
// grails-app/services/bindingdemo/WidgetService.groovy package bindingdemoclass WidgetService {
def updateWidget(Widget widget, Map data) { // this will throw an exception because // properties is read-only widget.properties = data } }
An instance of the data binder is in the Spring application context with a bean name of grailsWebDataBinder
. That bean implements the DataBinder interface. The following code demonstrates using the data binder directly.
// grails-app/services/bindingdmeo/WidgetService package bindingdemoimport org.grails.databinding.SimpleMapDataBindingSource
class WidgetService {
// this bean will be autowired into the service def grailsWebDataBinder
def updateWidget(Widget widget, Map data) { grailsWebDataBinder.bind widget, data as SimpleMapDataBindingSource }
}
See the DataBinder documentation for more information about overloaded versions
of the bind
method.
データバインディングとセキュリティ考慮
def p = Person.get(1)p.properties['firstName','lastName'] = params
firstName
and lastName
properties will be bound.firstName
とlastName
のみバインドされます。bindData
method allows the same data binding capability, but to arbitrary objects:bindData
メソッドは任意のオブジェクトに同様のデータバインディングができます:def p = new Person()
bindData(p, params)
bindData
method also lets you exclude certain parameters that you don't want updated:bindData
メソッドでは、更新したくないパラメータを除外することができます:def p = new Person()
bindData(p, params, [exclude: 'dateOfBirth'])
def p = new Person()
bindData(p, params, [include: ['firstName', 'lastName']])
Note that if an empty List is provided as a value for the空のリストがinclude
parameter then all fields will be subject to binding if they are not explicitly excluded.include
パラメータの値として与えられた場合、明示的に除外指定がなされていない限り、すべてのフィールドがバインディング対象となることに注意してください。
7.1.7 XMLとJSONのレスポンス
renderメソッドでXMLを出力する Using the render method to output XML
render
method can be passed a block of code to do mark-up building in XML:render
メソッドに、マークアップビルダーのコードブロックを渡してXML生成:def list() {def results = Book.list()
render(contentType: "text/xml") { books { for (b in results) { book(title: b.title) } } } }
<books> <book title="The Stand" /> <book title="The Shining" /> </books>
def list() {def books = Book.list() // naming conflict here
render(contentType: "text/xml") { books { for (b in results) { book(title: b.title) } } } }
books
which Groovy attempts to invoke as a method.renderメソッドでJSONを出力する Using the render method to output JSON
render
method can also be used to output JSON:render
メソッドが使用できます:def list() {def results = Book.list()
render(contentType: "application/json") { books = array { for (b in results) { book title: b.title } } } }
[ {"title":"The Stand"}, {"title":"The Shining"} ]
自動XMLマーシャリング Automatic XML Marshalling
grails.converters
package into your controller:grails.converters
パッケージをインポートする必要があります:import grails.converters.*
render Book.list() as XML
<?xml version="1.0" encoding="ISO-8859-1"?> <list> <book id="1"> <author>Stephen King</author> <title>The Stand</title> </book> <book id="2"> <author>Stephen King</author> <title>The Shining</title> </book> </list>
def xml = Book.list().encodeAsXML() render xml
自動JSONマーシャリング Automatic JSON Marshalling
XML
with JSON
:XML
と同じ仕組みで、JSON
の自動マーシャリングもサポートしています。単純に先のXML
をJSON
にするだけですrender Book.list() as JSON
[ {"id":1, "class":"Book", "author":"Stephen King", "title":"The Stand"}, {"id":2, "class":"Book", "author":"Stephen King", "releaseDate":new Date(1194127343161), "title":"The Shining"} ]
encodeAsJSON
to achieve the same effect.encodeAsJSON
も同じ結果になります。
7.1.8 JSONBuilder (JSONビルダー)
JSONBuilderとGrailsのバージョン JSONBuilder and Grails versions
JSONBuilder
class is used with the render
method for older applications; to use the newer/better JSONBuilder
class set the following in Config.groovy
:render
メソッドで古いJSONBuilder
を使用するようになっています。新しい良くなったJSONBuilder
を使用するにはConfig.groovy
に、次のような設定をします:grails.json.legacy.builder = false
単純なオブジェクトを描写 Rendering Simple Objects
render(contentType: "application/json") { hello = "world" }
{"hello":"world"}
JSON配列描写 Rendering JSON Arrays
render(contentType: "application/json") {
categories = ['a', 'b', 'c']
}
{"categories":["a","b","c"]}
render(contentType: "application/json") { categories = [ { a = "A" }, { b = "B" } ] }
{"categories":[ {"a":"A"} , {"b":"B"}] }
element
method to return a list as the root:element
メソッドを使用することで、リストをルートとして返す事ができます:render(contentType: "application/json") {
element 1
element 2
element 3
}
[1,2,3]
複雑なオブジェクトの描写 Rendering Complex Objects
render(contentType: "application/json") { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } }
{"categories":["a","b","c"],"title":"Hello JSON","information":{"pages":10}}
複雑なオブジェクトの配列 Arrays of Complex Objects
render(contentType: "application/json") { categories = [ { a = "A" }, { b = "B" } ] }
array
method to build them up dynamically:array
メソッドを使用して動的に生成する事もできます:def results = Book.list() render(contentType: "application/json") { books = array { for (b in results) { book title: b.title } } }
JSONBuilder APIに直接アクセスする Direct JSONBuilder API Access
render
method, but still want to produce JSON you can use the API directly:def builder = new JSONBuilder()def result = builder.build { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } }
// prints the JSON text println result.toString()
def sw = new StringWriter() result.render sw
7.1.9 ファイルアップロード
プログラムによるファイルアップロード Programmatic File Uploads
Upload Form: <br /> <g:uploadForm action="upload"> <input type="file" name="myFile" /> <input type="submit" /> </g:uploadForm>
uploadForm
tag conveniently adds the enctype="multipart/form-data"
attribute to the standard <g:form>
tag.uploadForm
タグは、通常の<g:form>
タグに、enctype="multipart/form-data"
の属性を追加します。def upload() { def f = request.getFile('myFile') if (f.empty) { flash.message = 'file cannot be empty' render(view: 'uploadForm') return }f.transferTo(new File('/some/local/dir/myfile.txt')) response.sendError(200, 'Done') }
InputStream
and so on with the MultipartFile interface.InputStream
を取得して直接ファイルを操作したりなど便利です。データバインディング経由のファイルアップロード File Uploads through Data Binding
Image
domain class:Image
というドメインクラスがあるとします:class Image { byte[] myFilestatic constraints = { // Limit upload file size to 2MB myFile maxSize: 1024 * 1024 * 2 } }
params
object in the constructor as in the example below, Grails will automatically bind the file's contents as a byte
to the myFile
property:params
をコンストラクタに渡してImageオブジェクトを生成すると、Grailsが自動的にファイルのコンテントをmyFile
プロパティにbyte[]
としてバインドします:def img = new Image(params)
byte
properties.byte[]
プロパティで指定した場合のblobのデフォルトサイズが255バイトになります。myFile
property on the image to a String type:myFile
プロパティの型をString型にすることで文字列にすることも可能です:class Image {
String myFile
}
7.1.10 コマンドオブジェクト
Grailsのコマンドオブジェクトの設計概念をサポートしています。 コマンドオブジェクトは data binding と連結して使用するクラスであり、通常ドメインクラスとして扱わないデータに対してバリデーションを可能にします。
Note: A class is only considered to be a command object when it is used as a parameter of an action.
コマンドオブジェクトの宣言 Declaring Command Objects
@grails.validation.Validateable class LoginCommand { String username String passwordstatic constraints = { username(blank: false, minSize: 6) password(blank: false, minSize: 6) } }
In this example, the command object is marked with the Validateable
annotation. The Validateable
annotation allows the definition of constraints just like in domain classes. If the command object is defined in the same source file as the controller that is using it, Grails will automatically mark it as Validateable
. It is not required that command object classes be validateable.
コマンドオブジェクトを使用する Using Command Objects
To use command objects, controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create and initialize.
Before the controller action is executed Grails will automatically create an instance of the command object class and populate its properties by binding the request parameters. If the command object class is marked with Validateable
then the command object will be validated. For example:
class LoginController {def login(LoginCommand cmd) { if (cmd.hasErrors()) { redirect(action: 'loginForm') return }
// work with the command object data } }
If the command object's type is that of a domain class and there is an id
request parameter then instead of invoking the domain class constructor to create a new instance a call will be made to the static get
method on the domain class and the value of the id
parameter will be passed as an argument. Whatever is returned from that call to get
is what will be passed into the controller action. This means that if there is an id
request parameter and no corresponding record is found in the database then the value of the command object will be null
.
コマンドオブジェクトと依存注入 Command Objects and Dependency Injection
@grails.validation.Validateable class LoginCommand {def loginService
String username String password
static constraints = { username validator: { val, obj -> obj.loginService.canLogin(obj.username, obj.password) } } }
loginService
bean which is injected by name from the Spring ApplicationContext
.loginService
をSpringのApplicatinContext
から名前解決でコマンドオブジェクトに注入しています。Binding The Request Body To Command Objects
When a request is made to a controller action which accepts a command object and the request contains a body, Grails will attempt to parse the body of the request based on the request content type and use the body to do data binding on the command object. See the following example.
// grails-app/controllers/bindingdemo/DemoController.groovy package bindingdemoclass DemoController {
def createWidget(Widget w) { render "Name: ${w?.name}, Size: ${w?.size}" } }
class Widget { String name Integer size }
$ curl -H "Content-Type: application/json" -d '{"name":"Some Widget","size":"42"}' localhost:8080/myapp/demo/createWidget Name: Some Widget, Size: 42 ~ $ $ curl -H "Content-Type: application/xml" -d '<widget><name>Some Other Widget</name><size>2112</size></widget>' localhost:8080/bodybind/demo/createWidget Name: Some Other Widget, Size: 2112 ~ $
Note that the body of the request is being parsed to make that work. Any attempt to read the body of the request after that will fail since the corresponding input stream will be empty. The controller action can either use a command object or it can parse the body of the request on its own (either directly, or by referring to something like request.JSON), but cannot do both.
// grails-app/controllers/bindingdemo/DemoController.groovy package bindingdemoclass DemoController {
def createWidget(Widget w) { // this will fail because it requires reading the body, // which has already been read. def json = request.JSON
// ...
} }
7.1.11 フォーム二重送信のハンドリング
<g:form useToken="true" ...>
withForm { // good request }.invalidToken { // bad request }
invalidToken
method then by default Grails will store the invalid token in a flash.invalidToken
variable and redirect the request back to the original page. This can then be checked in the view:invalidToken
にチェインしなかった場合は、デフォルトでGrailsが無効トークンをflash.invalidToken
に保持して、元のページにリクエストをリダイレクトします。これによってビューで以下のように確認できます:
<g:if test="${flash.invalidToken}"> Don't click the button twice! </g:if>
The withForm tag makes use of the session and hence requires session affinity or clustered sessions if used in a cluster.withFormメソッドはセッション(session)を使用するので、セッションの類似性またはクラスタで使用する場合はクラスタ化されたセッションが必要です。
7.1.12 シンプルタイプコンバータ
型変換メソッド Type Conversion Methods
def total = params.int('total')
int
method, and there are also methods for boolean
, long
, char
, short
and so on. Each of these methods is null-safe and safe from any parsing errors, so you don't have to perform any additional checks on the parameters.boolean
,long
,char
,short
等多数のメソッドがあります。これらのメソッドはnullセーフであり、パースエラーセーフなので、パラメータに対してのチェックを追加する必要がありません。
def total = params.int('total', 42)
attrs
parameter of GSP tags.attrs
パラメータでも、同じ仕組みの型変換機能が使用できます。複数の同一名称パラメータのハンドリング Handling Multi Parameters
?name=Bob&name=Judy
."?name=Bob&name=Judy"
等。String
iterate over each character. To avoid this problem the params object provides a list
method that always returns a list:String
の文字列が1文字ずつ参照されてしまいます。この問題を避けるために、paramsオブジェクトのlist
メソッドを使用することで毎回リストを返すことが可能です:for (name in params.list('name')) {
println name
}
7.1.13 コントローラ例外ハンドリング宣言
Grails controllers support a simple mechanism for declarative exception handling. If a controller declares a method that accepts a single argument and the argument type isjava.lang.Exception
or some subclass of java.lang.Exception
, that method will be invoked any time an action in that controller throws an exception of that type. See the following example.// grails-app/controllers/demo/DemoController.groovy package democlass 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'] } }
That controller will behave as if it were written something like this...
// grails-app/controllers/demo/DemoController.groovy package democlass DemoController {
def someAction() { try { // do some work } catch (BatchUpdateException e) { return handleBatchUpdateException(e) } catch (SQLException e) { return handleSQLException(e) } catch (NumberFormatException e) { return handleNumberFormatException(e) } }
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'] } }
The exception handler method names can be any valid method name. The name is not what makes the method an exception handler, the Exception
argument type is the important part.
The exception handler methods can do anything that a controller action can do including invoking render
, redirect
, returning a model, etc. The exception handler methods are inherited into sublcasses so an application could define the exception handlers in an abstract class that multiple controllers extend from.
Exception handler methods must be present at compile time. Specifically, exception handler methods which are runtime metaprogrammed onto a controller class are not supported.
7.2 Groovyサーバーページ
grails-app/views
directory and are typically rendered automatically (by convention) or with the render method such as:render(view: "index")
Although it is possible to have Groovy logic embedded in your GSP and doing this will be covered in this document, the practice is strongly discouraged. Mixing mark-up and code is a bad thing and most GSP pages contain no code and needn't do so.GroovyロジックをGSPに埋め込むことも可能ですが推奨しません。マークアップとコードが混在するのは良いことではありません。ほとんどのGSPではコードを持つべきで無く、そうする必要がありません。
def show() { [book: Book.get(params.id)] }
Book
instance and create a model that contains a key called book
. This key can then be referenced within the GSP view using the name book
:Book
インスタンスを取り出して、book
というキーでモデルを作成しています。GSPでは、このキーbook
が参照できます。${book.title}
Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on XSS prevention for information on how to prevent XSS attacks.
7.2.1 GSPの基本
<% %>
scriptlet blocks to embed Groovy code (again this is discouraged):<% %>
をサポートしています。(しつこいですが推奨しません)<html> <body> <% out << "Hello GSP!" %> </body> </html>
<%= %>
syntax to output values:<%= %>
を使用して値を出力することもできます。<html> <body> <%="Hello GSP!" %> </body> </html>
<html> <body> <%-- This is my comment --%> <%="Hello GSP!" %> </body> </html>
Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on XSS prevention for information on how to prevent XSS attacks.
7.2.1.1 変数とスコープ
<% %>
brackets you can declare variables:<% %>
で変数を宣言できます。<% now = new Date() %>
<%=now%>
application
- The javax.servlet.ServletContext instanceapplicationContext
The Spring ApplicationContext instanceflash
- The flash objectgrailsApplication
- The GrailsApplication instanceout
- The response writer for writing to the output streamparams
- The params object for retrieving request parametersrequest
- The HttpServletRequest instanceresponse
- The HttpServletResponse instancesession
- The HttpSession instancewebRequest
- The GrailsWebRequest instance
application
- javax.servlet.ServletContextインスタンスapplicationContext
- Spring ApplicationContextインスタンスflash
- flash オブジェクトgrailsApplication
- GrailsApplicationインスタンスout
- 出力ストリームを書き込むレスポンスライターparams
- paramsリクエストパラメータを取得するオブジェクトrequest
- HttpServletRequestインスタンスresponse
- HttpServletResponseインスタンスsession
- HttpSessionインスタンスwebRequest
- GrailsWebRequestインスタンス
7.2.1.2 ロジックとイテレーション
<% %>
syntax you can embed loops and so on using this syntax:<% %>
シンタックスを使ってループなどを記述できます。<html> <body> <% [1,2,3,4].each { num -> %> <p><%="Hello ${num}!" %></p> <%}%> </body> </html>
<html> <body> <% if (params.hello == 'true')%> <%="Hello!"%> <% else %> <%="Goodbye!"%> </body> </html>
7.2.1.3 ページディレクティブ
<%@ page import="java.awt.*" %>
<%@ page contentType="application/json" %>
7.2.1.4 エクスプレッション
<%= %>
syntax introduced earlier is rarely used due to the support for GSP expressions. A GSP expression is similar to a JSP EL expression or a Groovy GString and takes the form ${expr}
:<%= %>
シンタックスは滅多に使用しません。代わりに、JSPの式言語(JSP EL)と同じような機能をもつGSP(Groovy)表記または、${expr}
のようなGroovyのGStringを使用します。
<html> <body> Hello ${params.name} </body> </html>
${..}
block. ${…}
ブロックに記述します。Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on XSS prevention for information on how to prevent XSS attacks.
7.2.2 GSPタグ
The section on Tag Libraries covers how to add your own custom tag libraries.カスタムタグの追加などは、タグライブラリのセクションで解説します。
g:
. Unlike JSP, you don't specify any tag library imports. If a tag starts with g:
it is automatically assumed to be a GSP tag. An example GSP tag would look like:g:
で始まるタグです。JSPと違いタグライブラリのインポートが必要有りません。g:
接頭辞のタグは自動的にGSPタグとして用いられます。例としてGSPタグの見ためは次のようになります:<g:example />
<g:example> Hello world </g:example>
<g:example attr="${new Date()}"> Hello world </g:example>
<g:example attr="${new Date()}" attr2="[one:1, two:2, three:3]"> Hello world </g:example>
<g:example attr="${new Date()}" attr2="[one:'one', two:'two']"> Hello world </g:example>
7.2.2.1 変数とスコープ
<g:set var="now" value="${new Date()}" />
now
to the result of a GSP expression (which simply constructs a new java.util.Date
instance). You can also use the body of the <g:set>
tag to define a variable:now
にGSP表記の結果を割り当てています(単純にjava.util.Date
のインスタンスを生成しただけです)。<g:set>
タグのタグ内容に記述して定義することもできます。:<g:set var="myHTML"> Some re-usable code on: ${new Date()} </g:set>
<g:set var="bookService" bean="bookService" />
page
- Scoped to the current page (default)request
- Scoped to the current requestflash
- Placed within flash scope and hence available for the next requestsession
- Scoped for the user sessionapplication
- Application-wide scope.
page
- (デフォルト)現在のページrequest
- 現在のリクエストflash
- flashスコープに配置され、次のリクエストまで。session
- ユーザのセッションapplication
- アプリケーション全体
scope
attribute:scope
属性に指定します:<g:set var="now" value="${new Date()}" scope="request" />
7.2.2.2 ロジックとイテレーション
<g:if test="${session.role == 'admin'}"> <%-- show administrative functions --%> </g:if> <g:else> <%-- show basic functions --%> </g:else>
<g:each in="${[1,2,3]}" var="num"> <p>Number ${num}</p> </g:each><g:set var="num" value="${1}" /> <g:while test="${num < 5 }"> <p>Number ${num++}</p> </g:while>
7.2.2.3 検索とフィルタリング
Stephen King's Books: <g:findAll in="${books}" expr="it.author == 'Stephen King'"> <p>Title: ${it.title}</p> </g:findAll>
expr
attribute contains a Groovy expression that can be used as a filter. The grep tag does a similar job, for example filtering by class:expr
属性に記述します。grepタグも同じような動作をします。クラスでのフィルタリングを例とすると:<g:grep in="${books}" filter="NonFictionBooks.class"> <p>Title: ${it.title}</p> </g:grep>
<g:grep in="${books.title}" filter="~/.*?Groovy.*?/"> <p>Title: ${it}</p> </g:grep>
books
variable is a collection of Book
instances. Since each Book
has a title
, you can obtain a list of Book titles using the expression books.title
. Groovy will auto-magically iterate the collection, obtain each title, and return a new list!books
はBook
インスタンスのコレクションです。全てのBook
にプロパティtitle
が有る場合、books.title
とすることでBook
のtitle
プロパティのリストを得られます。Groovyは自動的にコレクションを検索して全てのtitle
を含んだリストを返してくれます。
7.2.2.4 リンクとリソース
<g:link action="show" id="1">Book 1</g:link><g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
<g:link controller="book">Book Home</g:link>
<g:link controller="book" action="list">Book List</g:link>
<g:link url="[action: 'list', controller: 'book']">Book List</g:link>
<g:link params="[sort: 'title', order: 'asc', author: currentBook.author]" action="list">Book List</g:link>
7.2.2.5 フォームとフィールド
フォームの基礎 Form Basics
url
attribute lets you specify which controller and action to map to:url
属性にマップでコントローラアクションを指定します:<g:form name="myForm" url="[controller:'book',action:'list']">...</g:form>
myForm
that submits to the BookController
's list
action. Beyond that all of the usual HTML attributes apply.myForm
という名称で、BookController
のlist
アクションへ送信するフォームを生成します。通常のHTML属性はそのまま使用できます。フォームフィールド Form Fields
- textField - For input fields of type 'text'
- passwordField - For input fields of type 'password'
- checkBox - For input fields of type 'checkbox'
- radio - For input fields of type 'radio'
- hiddenField - For input fields of type 'hidden'
- select - For dealing with HTML select boxes
- textField - 属性typeが'text'のinputタグ用
- passwordField - 属性typeが'password'のinputタグ用
- checkBox - 属性typeが'checkbox'のinputタグ用
- radio - 属性typeが'radio'のinputタグ用
- hiddenField - 属性typeが'hidden'のinputタグ用
- select - セレクトボックス用タグ
<g:textField name="myField" value="${myValue}" />
マルチ送信ボタン Multiple Submit Buttons
<g:actionSubmit value="Some update label" action="update" />
7.2.2.6 タグをメソッドとして使用
GSPでタグをメソッドとして使用する Tags as method calls from GSPs
StreamCharBuffer
which has all of the same methods as String) instead of writing directly to the response when called as methods. For example:StreamCharBuffer
)。:Static Resource: ${createLinkTo(dir: "images", file: "logo.jpg")}
<img src="${createLinkTo(dir: 'images', file: 'logo.jpg')}" />
<img src="<g:createLinkTo dir="images" file="logo.jpg" />" />
コントローラとタグライブラリでタグをメソッドとして使用する Tags as method calls from Controllers and Tag Libraries
g:
namespace can be invoked without the prefix and a StreamCharBuffer
result is returned:g:
を持つタグは、接頭辞無しで呼び出す事で、結果にStreamCharBuffer
を返します:def imageLocation = createLinkTo(dir:"images", file:"logo.jpg").toString()
def imageLocation = g.createLinkTo(dir:"images", file:"logo.jpg").toString()
def editor = fckeditor.editor(name: "text", width: "100%", height: "400")
7.2.3 ビューとテンプレート
テンプレートの基礎 Template Basics
grails-app/views/book/_bookTemplate.gsp
:grails-app/views/books/
に _bookTemplate.gsp
として配置:<div class="book" id="${book?.id}"> <div>Title: ${book?.title}</div> <div>Author: ${book?.author?.name}</div> </div>
Use the render tag to render this template from one of the views in grails-app/views/book
:
grails-app/views/book
の配置したビューで、テンプレートを使用するには、renderタグを使います:
<g:render template="bookTemplate" model="[book: myBook]" />
model
attribute of the render
tag. If you have multiple Book
instances you can also render the template for each Book
using the render tag with a collection
attribute:Book
インスタンスを使用して、それぞれのBook
をテンプレートで描写する場合は、以下のようにrender
タグのcollection
属性にコレクションを指定します:<g:render template="bookTemplate" var="book" collection="${bookList}" />
テンプレートの共有 Shared Templates
BookController
and its views at grails-app/views/book
. However, you may want to share templates across your application.BookController
とgrails-app/views/book
階層以下のビューを対象に説明しました。テンプレートはアプリケーション全体を通して使用したいと思います。/
instead of a relative location. For example if you had a template called grails-app/views/shared/_mySharedTemplate.gsp
, you would reference it as:/(スラッシュ)
から始まる grails-app/viewsからの絶対パスで指定します。例として、テンプレートファイルが、grails-app/views/shared/_mySharedTemplate.gsp
だとした場合は次のように指定します:<g:render template="/shared/mySharedTemplate" />
<g:render template="/book/bookTemplate" model="[book: myBook]" />
テンプレートネームスペース The Template Namespace
tmpl
, available that makes using templates easier. Consider for example the following usage pattern:tmpl
という名称の、テンプレートネームスペースが使用できます:<g:render template="bookTemplate" model="[book:myBook]" />
This can be expressed with the tmpl
namespace as follows:
上記の例をtmpl
ネームスペースで記述すると以下のようになります:
<tmpl:bookTemplate book="${myBook}" />
コントローラとタグライブラリでのテンプレート Templates in Controllers and Tag Libraries
def bookData() {
def b = Book.get(params.id)
render(template:"bookTemplate", model:[book:b])
}
def bookData() { def b = Book.get(params.id) String content = g.render(template:"bookTemplate", model:[book:b]) render content }
g
namespace which tells Grails we want to use the tag as method call instead of the render method.g
を使用することでタグをメソッドとして使用するのか、コントローラのrenderメソッドなのかを区別しています。
7.2.4 Sitemeshでレイアウト
レイアウトを作成する Creating Layouts
grails-app/views/layouts
directory. A typical layout can be seen below:grails-app/views/layouts
ディレクトリに配置します。標準的なレイアウトは以下のようになります:<html> <head> <title><g:layoutTitle default="An example decorator" /></title> <g:layoutHead /> </head> <body onload="${pageProperty(name:'body.onload')}"> <div class="menu"><!--my common menu goes here--></menu> <div class="body"> <g:layoutBody /> </div> </div> </body> </html>
layoutTitle
- outputs the target page's titlelayoutHead
- outputs the target page's head tag contentslayoutBody
- outputs the target page's body tag contents
layoutTitle
- ページのタイトルを出力layoutHead
- ページのheadタグコンテントを出力layoutBody
- ページのbodyタグコンテントを出力
レイアウトを反映させる Triggering Layouts
<html> <head> <title>An Example Page</title> <meta name="layout" content="main" /> </head> <body>This is my content!</body> </html>
grails-app/views/layouts/main.gsp
will be used to layout the page. If we were to use the layout from the previous section the output would resemble this:grails-app/views/layouts/main.gsp
が呼び出されてページのレイアウトに使用されます。内容が先ほどのレイアウトの内奥であれば、以下のような出力が得られます:<html> <head> <title>An Example Page</title> </head> <body onload=""> <div class="menu"><!--my common menu goes here--></div> <div class="body"> This is my content! </div> </body> </html>
コントローラでレイアウトを指定 Specifying A Layout In A Controller
class BookController { static layout = 'customer'def list() { … } }
grails-app/views/layouts/customer.gsp
which will be applied to all views that the BookController
delegates to. The value of the "layout" property may contain a directory structure relative to the grails-app/views/layouts/
directory. For example:grails-app/views/layouts/customer.gspと
いうレイアウトファイルを作成すると、BookController
に連動する全てのビューに反映します。
"layout"プロパティの値はgrails-app/views/layouts/
ディレクトリが含まれます。例として:class BookController { static layout = 'custom/customer'def list() { … } }
Views rendered from that controller would be decorated with the grails-app/views/layouts/custom/customer.gsp
template.
この例で、このコントローラのビューは、grails-app/views/layouts/custom/customer.gsp
テンプレートでデコレートされます。
慣習によるレイアウト Layout by Convention
class BookController { def list() { … } }
grails-app/views/layouts/book.gsp
, which will be applied to all views that the BookController
delegates to.BookController
のビューに反映されるレイアウトgrails-app/views/layouts/book.gsp
を作成できます。grails-app/views/layouts/book/list.gsp
which will only be applied to the list
action within the BookController
.BookController
のアクションlist
のみに反映するレイアウトgrails-app/views/layouts/book/list.gsp
を作成できます。grails-app/views/layouts/application.gsp
. The name of the application default layout may be changed by defining a property
in grails-app/conf/Config.groovy
as follows:grails-app/views/layouts/application.gsp
を探しに行きます。アプリケーションのデフォルトレイアウト名称は、次のプロパティをgrails-app/conf/Config.groovy
に定義することで変更が可能です。:grails.sitemesh.default.layout = 'myLayoutName'
grails-app/views/layouts/myLayoutName.gsp
.grails-app/views/layouts/myLayoutName.gsp
になります。インラインレイアウト Inline Layouts
<g:applyLayout name="myLayout" template="bookTemplate" collection="${books}" /><g:applyLayout name="myLayout" url="http://www.google.com" />
<g:applyLayout name="myLayout"> The content to apply a layout to </g:applyLayout>
サーバーサイドインクルード Server-Side Includes
<g:include controller="book" action="list" />
<g:applyLayout name="myLayout"> <g:include controller="book" action="list" /> </g:applyLayout>
def content = include(controller:"book", action:"list")
7.2.5 静的リソース
- Web application performance tuning is difficult
- Correct ordering of resources, and deferred inclusion of JavaScript
- Resources that depend on others that must be loaded first
- The need for a standard way to expose static resources in plugins and applications
- The need for an extensible processing chain to optimize resources
- Preventing multiple inclusion of the same resource
- Webアプリケーションのパフォーマンスチューニングが難しい
- リソースの配置順と、JavaScriptの遅延包括
- 先に読み込む必要のある依存関係のあるリソース
- プラグインやアプリケーションでの、静的リソースを表示する方法の標準化が必要
- リソースの最適化を行うための拡張可能な連鎖行程が必要
- 同じリソースの多重配置を防ぐ
7.2.5.1 リソースタグでのリソースの使用
r:requireでリソースを制御する Pulling in resources with r:require
<html> <head> <r:require module="jquery"/> <r:layoutResources/> </head> <body> … <r:layoutResources/> </body> </html>
r:require
multiple times in a GSP page, and you use the "modules" attribute to provide a list of modules:r:require
を複数回呼んでも構いません。そして"modules"属性を使用してモジュールを列挙することもできます:<html> <head> <r:require modules="jquery, main, blueprint, charting"/> <r:layoutResources/> </head> <body> … <r:layoutResources/> </body> </html>
<r:layoutResources/>
タグが必要になります。r:layoutResourcesでリソースへのリンクを描写する Rendering the links to resources with r:layoutResources
<html> <head> <g:layoutTitle/> <r:layoutResources/> </head> <body> <g:layoutBody/> <r:layoutResources/> </body> </html>
r:scriptでページ固有のJavaScriptコードを追加 Adding page-specific JavaScript code with r:script
r:script
directly when you need to include fragments of JavaScript code.r:script
を呼ぶことを推奨します。<html> <head> <g:layoutTitle/> <r:layoutResources/> </head> <body> <g:layoutBody/> <r:layoutResources/> </body> </html>
<html> <head> <title>Testing r:script magic!</title> </head> <body> <r:script disposition="head"> window.alert('This is at the end of <head>'); </r:script> <r:script disposition="defer"> window.alert('This is at the end of the body, and the page has loaded.'); </r:script> </body> </html>
r:imgで画像へのリンク Linking to images with r:img
<img>
markup, using the Resources framework to process the resource on the fly (if configured to do so - e.g. make it eternally cacheable).<img>
tag if the resource has been previously declared in a module.<img>
タグの属性に追加します。<html> <head> <title>Testing r:img</title> </head> <body> <r:img uri="/images/logo.png"/> </body> </html>
g:img
tag as a shortcut for rendering <img>
tags that refer to a static resource. The Grails img tag is Resources-aware and will delegate to r:img
if found. However it is recommended that you use r:img
directly if using the Resources plugin.<img>
タグを描写する、リソース参照できるg:img
タグが存在します。Grailsのimgタグは、存在した場合リソースフレームワークが認識してr:img
に委譲しますが、リソースプラグインを使用している場合は直接r:img
を使用することを推奨します。7.2.5.2 他のリソースタグ
r:resource
g:resource
tag delegates to this implementation if found, but if your code requires the Resources plugin, you should use r:resource
directly.g:resource
タグが有った場合はこのタグに委譲します。リソースプラグインを使用している場合は直接r:resource
を使用しましょう。
r:external
7.2.5.3 リソースの宣言
Config.groovy
in the case of application-specific resources, or more commonly in a resources artefact in grails-app/conf
.Config.groovy
ファイルに記述、また通常はリソースアーテファクトとしてgrails-app/conf
にファイルで配置します。grails-app/conf/MyAppResources.groovy
:grails-app/conf/MyAppResources.groovy
ファイルで例として有るとします:modules = { core { dependsOn 'jquery, utils'resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js' resource url: '/css/main.css', resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] }
utils { dependsOn 'jquery'
resource url: '/js/utils.js' }
forms { dependsOn 'core,utils'
resource url: '/css/forms.css' resource url: '/js/forms.js' } }
bundle:'someOtherName'
on each resource, or call defaultBundle
on the module (see resources plugin documentation).bundle:'someOtherName'
またはモジュールでdefaultBundle
を呼ぶことででオーバーライドできます。(Resourcesプラグインドキュメントを参照)dependsOn
, which controls the load order of the resources.dependsOn
で宣言しています。<r:require module="forms"/>
in your GSP, it will pull in all the resources from 'core' and 'utils' as well as 'jquery', all in the correct order.<r:require module="forms"/>
を含んだ場合、この例では'core','util'そして'jquery'のリソースを正常な順番で引っ張ります。disposition:'head'
on the core.js
file. This tells Resources that while it can defer all the other JS files to the end of the body, this one must go into the <head>
.disposition:'head'
に注目してください。その他全てのリソースはボディの最後に配置して、このファイルは必ず<head>
に配置する指定をしています。attrs
map option, and these are passed through to the r:external
tag when the engine renders the link to the resource, so you can customize the HTML attributes of the generated link.attrs
マップで追加しています。そしてこれらはr:external
タグを通してリソースへのリンクを形成します。これによってリンクのHTML属性をカスタマイズすることができます。grails.resources.modules
Config variable.grails.resources.modules
に定義します。7.2.5.4 プラグインリソースのオーバーライド
defaultBundle
setting for a module, or attributes of individual resources that have been declared with a unique id:defaultBundle
設定で定義した名称を指定する、DSLの"overrides"で対応しています。modules = { core { dependsOn 'jquery, utils' defaultBundle 'monolith'resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js' resource url: '/css/main.css', resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] }
utils { dependsOn 'jquery' defaultBundle 'monolith'
resource url: '/js/utils.js' }
forms { dependsOn 'core,utils' defaultBundle 'monolith'
resource url: '/css/forms.css' resource url: '/js/forms.js' }
overrides { jquery { defaultBundle 'monolith' } } }
For full details of the resource DSL please see the resources plugin documentation. リソースDSLの詳細はリソースプラグインのドキュメントを参考にしてください。
7.2.5.5 リソースの最適化
複数のリソースを少ないファイルにまとめる Bundling multiple resources into fewer files
defaultBundle
clause on the module. Modules have an implicit default bundle name the same as the name of the module.defaultBundle
に継承されたリソースに対してデフォルトで操作します。モジュールはモジュール名と同じ名称で、暗黙なデフォルトバンドル名を持っています。modules = { core { dependsOn 'jquery, utils' defaultBundle 'common'resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js', bundle: 'ui' resource url: '/css/main.css', bundle: 'theme' resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] }
utils { dependsOn 'jquery'
resource url: '/js/utils.js', bundle: 'common' }
forms { dependsOn 'core,utils'
resource url: '/css/forms.css', bundle: 'ui' resource url: '/js/forms.js', bundle: 'ui' } }
クライアントのブラウザでリソースを"永久的に"キャッシュさせる Making resources cache "eternally" in the client browser
リソース(Zip)圧縮 Zipping resources
最小化(Minifying) Minifying
7.2.5.6 デバッグ
X-Grails-Resources-Original-Srcヘッダー X-Grails-Resources-Original-Src Header
デバッグフラグを追加 Adding the debug flag
常にデバッグを有効にする Turning on debug all the time
grails.resources.debug = true
7.2.5.7 リソース生成・変換処理を防ぐ
個々のリソースの特定のマッパー処理を防ぐ Preventing the application of a specific mapper to an individual resource
modules = { forms { resource url: '/css/forms.css', nohashandcache: true resource url: '/js/forms.js', nohashandcache: true } }
特定のマッパーでの、パス、ファイルタイプの除外と包含 Excluding/including paths and file types from specific mappers
Config.groovy
using the mapper name e.g:Config.groovy
にマッパー名で定義することができます:// We wouldn't link to .exe files using Resources but for the sake of example: grails.resources.zip.excludes = ['**/*.zip', '**/*.exe']// Perhaps for some reason we want to prevent bundling on "less" CSS files: grails.resources.bundle.excludes = ['**/*.less']
"ad-hoc"(レガシー)リソースとして扱う物の操作 Controlling what is treated as an "ad-hoc" (legacy) resource
grails.resources.adhoc.patterns = ['images/*', '*.js', '*.css']
7.2.5.8 リソース関連のプラグイン
7.2.6 Sitemeshコンテントブロック
<content>
tag:<content>
タグでページ内をブロック分割します。<content tag="navbar"> … ここにナビゲーションバーコンテンツ… </content><content tag="header"> … ここにヘッダーコンテンツ… </content>
<content tag="footer"> … ここにフッターコンテンツ… </content>
<content tag="body"> … ここにボディコンテンツ… </content>
<html> <body> <div id="header"> <g:applyLayout name="headerLayout"> <g:pageProperty name="page.header" /> </g:applyLayout> </div> <div id="nav"> <g:applyLayout name="navLayout"> <g:pageProperty name="page.navbar" /> </g:applyLayout> </div> <div id="body"> <g:applyLayout name="bodyLayout"> <g:pageProperty name="page.body" /> </g:applyLayout> </div> <div id="footer"> <g:applyLayout name="footerLayout"> <g:pageProperty name="page.footer" /> </g:applyLayout> </div> </body> </html>
7.2.7 デプロイされたアプリケーションへの変更
grails.gsp.view.dir
configuration setting.grails.gsp.view.dir
定義という解決方法が存在します。/var/www/grails/my-app
directory. We add these two lines to grails-app/conf/Config.groovy
:/var/www/grails/my-app
の階層はパックしないこととします。以下の2行をgrails-app/conf/Config.groovy
に追加します:grails.gsp.enable.reload = true grails.gsp.view.dir = "/var/www/grails/my-app/"
The trailing slash on thegrails.gsp.view.dir
value is important! Without it, Grails will look for views in the parent directory.grails.gsp.view.dir
の最後に付いているスラッシュは重要です。これが無いとGrailsが親ディレクトリにビューを探しに行きます。
mkdir -p /var/www/grails/my-app/grails-app/views cp -R grails-app/views/* /var/www/grails/my-app/grails-app/views
grails-app/views
bit. So you end up with the path /var/www/grails/my-app/grails-app/views/...
.grails-app/views
を含んだ全てのビューディレクトリ階層を持たなくてはならない所です。この場合だとパスは、/var/www/grails/my-app/grails-app/views/...
となります。Name | Description | Default |
---|---|---|
grails.gsp.enable.reload | altervative system property for enabling the GSP reload mode without changing Config.groovy | |
grails.gsp.reload.interval | interval between checking the lastmodified time of the gsp source file, unit is milliseconds | 5000 |
grails.gsp.reload.granularity | the number of milliseconds leeway to give before deciding a file is out of date. this is needed because different roundings usually cause a 1000ms difference in lastmodified times | 1000 |
名称 | 説明 | 既存値 |
---|---|---|
grails.gsp.enable.reload | Config.groovy変更せずにGSPリロードモードを許可にします。 | |
grails.gsp.reload.interval | gspソースファイルの更新を確認するインターバル。ミリ秒で指定。 | 5000 |
grails.gsp.reload.granularity | ファイルが更新されたかを判断する時間のゆとり。ミリ秒で指定。 | 1000 |
7.2.8 GSPデバッグ
生成されたソースコードを表示する Viewing the generated source code
- Adding "?showSource=true" or "&showSource=true" to the url shows the generated Groovy source code for the view instead of rendering it. It won't show the source code of included templates. This only works in development mode
- The saving of all generated source code can be activated by setting the property "grails.views.gsp.keepgenerateddir" (in Config.groovy) . It must point to a directory that exists and is writable.
- During "grails war" gsp pre-compilation, the generated source code is stored in grails.project.work.dir/gspcompile (usually in ~/.grails/(grails_version)/projects/(project name)/gspcompile).
- URLに、 "?showSource=true" または、"&showSource=true"を追加するとページ描写の代わりに、ビュー用に生成されたGroovyコードが参照できます。但し含んだテンプレートのコードは含まれません。開発モードのみで動作します。
- Config.groovyにプロパティ"grails.views.gsp.keepgenerateddir"を指定すると生成ファイルが指定された場所に保存されます。
- "grails war"でのgspプリコンパイル時に、生成されたソースコードがgrails.project.work.dir/gspcompileに保存されます。(通常は~/.grails/(grails_version)/projects/(project name)/gspcompileです。)
デバッガでGSPコードをデバッグ Debugging GSP code with a debugger
使用されたテンプレートの情報を参照 Viewing information about templates used to render a single url
g:render
taglib. Several small templates can be used to render a single page.
It might be hard to find out what GSP template actually renders the html seen in the result.
The debug templates -feature adds html comments to the output. The comments contain debug information about gsp templates used to render the page.g:render
タグを使用してGSPテンプレートは再利用されます。幾つかの小さなテンプレートが1つのページで使われる事もあります。どの部分でGSPテンプレートが実際にHTMLを描写したか探すのは大変だと思います。テンプレートデバッグ機能ではhtmlコメントでGSPテンプレートのデバッグ情報を提供します。
<!-- GSP #2 START template: /home/.../views/_carousel.gsp
precompiled: false lastmodified: … -->
.
.
.
<!-- GSP #2 END template: /home/.../views/_carousel.gsp
rendering time: 115 ms -->
7.3 タグライブラリ
TagLib
and place it within the grails-app/taglib
directory:grails-app/taglib
ディレクトリに、名称の最後がTagLib
となるGroovyクラスを作成します:class SimpleTagLib {}
class SimpleTagLib { def simple = { attrs, body ->} }
The attrs
argument is a Map of the attributes of the tag, whilst the body
argument is a Closure that returns the body content when invoked:
引数attrs
はタグ属性のMapです。引数body
はタグ内容のコンテンツを呼び出すクロージャです:
class SimpleTagLib { def emoticon = { attrs, body -> out << body() << (attrs.happy == 'true' ? " :-)" : " :-(") } }
out
variable that refers to the output Writer
which you can use to append content to the response. Then you can reference the tag inside your GSP; no imports are necessary:Writer
を参照する変数out
に対してコンテンツを追加しています。ここまで作成したら、以下のように、GSPの中でタグをそのまま参照します。importは必要ありません。:<g:emoticon happy="true">Hi John</g:emoticon>
To help IDEs like SpringSource Tool Suite (STS) and others autocomplete tag attributes, you should add Javadoc comments to your tag closures withタグリブはGroovyコードを使用しているため、タグで使用可能な属性全てを認識することは困難です。SpringSource Tool Suite (STS)等のIDEでの補完機能に対しての手助けとして、タグクロージャのJavadocコメント内に@attr
descriptions. Since taglibs use Groovy code it can be difficult to reliably detect all usable attributes.@attr
を含めましょう。For example:例として:class SimpleTagLib {/** * Renders the body with an emoticon. * * @attr happy whether to show a happy emoticon ('true') or * a sad emoticon ('false') */ def emoticon = { attrs, body -> out << body() << (attrs.happy == 'true' ? " :-)" : " :-(") } }
and any mandatory attributes should include the REQUIRED keyword, e.g.必須条件の属性には、キーワードREQUIREDを指定します。class SimpleTagLib {/** * Creates a new password field. * * @attr name REQUIRED the field name * @attr value the field value */ def passwordField = { attrs -> attrs.type = "password" attrs.tagName = "passwordField" fieldImpl(out, attrs) } }
7.3.1 変数とスコープ
actionName
- The currently executing action namecontrollerName
- The currently executing controller nameflash
- The flash objectgrailsApplication
- The GrailsApplication instanceout
- The response writer for writing to the output streampageScope
- A reference to the pageScope object used for GSP rendering (i.e. the binding)params
- The params object for retrieving request parameterspluginContextPath
- The context path to the plugin that contains the tag libraryrequest
- The HttpServletRequest instanceresponse
- The HttpServletResponse instanceservletContext
- The javax.servlet.ServletContext instancesession
- The HttpSession instance
actionName
- 現在実行中のアクション名controllerName
- 現在実行中のコントローラ名flash
- flashオブジェクトgrailsApplication
- GrailsApplicationインスタンスout
- 出力用のレスポンスライターpageScope
- GSP描写で使用するpageScopeオブジェクトへの参照params
- リクエストパラメータ取得用のparamsオブジェクトpluginContextPath
- タグライブラリを含むプラグインへのコンテキストパス。request
- HttpServletRequestインスタンスresponse
- HttpServletResponseインスタンスservletContext
- javax.servlet.ServletContext インスタンスsession
- HttpSessionインスタンス
7.3.2 簡単なタグ
dateFormat
style tag:dateFormat
タグを紹介します:def dateFormat = { attrs, body ->
out << new java.text.SimpleDateFormat(attrs.format).format(attrs.date)
}
SimpleDateFormat
class to format a date and then write it to the response. The tag can then be used within a GSP as follows:SimpleDateFormat
クラスを使ってフォーマットした日付をレスポンスに出力します。このタグは、GSPで次のように使用します:
<g:dateFormat format="dd-MM-yyyy" date="${new Date()}" />
def formatBook = { attrs, body -> out << "<div id="${attrs.book.id}">" out << "Title : ${attrs.book.title}" out << "</div>" }
def formatBook = { attrs, body ->
out << render(template: "bookTemplate", model: [book: attrs.book])
}
7.3.3 制御タグ
def isAdmin = { attrs, body ->
def user = attrs.user
if (user && checkUserPrivs(user)) {
out << body()
}
}
<g:isAdmin user="${myUser}"> // some restricted content </g:isAdmin>
7.3.4 イテレートタグ
def repeat = { attrs, body -> attrs.times?.toInteger()?.times { num -> out << body(num) } }
times
attribute and if it exists convert it to a number, then use Groovy's times
method to iterate the specified number of times:times
を有無や数値なのかを確認し、その数値でGroovyのtimes
メソッドを実行して、与えられた数値の回数、実行内容を繰り返します:<g:repeat times="3"> <p>Repeat this 3 times! Current repeat = ${it}</p> </g:repeat>
it
variable to refer to the current number. This works because when we invoked the body we passed in the current value inside the iteration:it
の使い方を紹介しています。これはbody実行時にイテレーションの数値をbodyに渡すことで動作しています。:out << body(num)
it
to the tag. However, if you have nested tags this can lead to conflicts, so you should should instead name the variables that the body uses:it
に渡されます。ただしタグをネストした場合は名称の衝突が起きるため違う名称を指定できるようにする必要があります。:def repeat = { attrs, body -> def var = attrs.var ?: "num" attrs.times?.toInteger()?.times { num -> out << body((var):num) } }
var
attribute and if there is use that as the name to pass into the body invocation on this line:out << body((var):num)
Note the usage of the parenthesis around the variable name. If you omit these Groovy assumes you are using a String key and not referring to the variable itself.変数名パーレン使用時の注意点です。これを省略するとGroovyは文字列キーとして解釈してしまい変数として参照できません。
<g:repeat times="3" var="j"> <p>Repeat this 3 times! Current repeat = ${j}</p> </g:repeat>
var
attribute to define the name of the variable j
and then we are able to reference that variable within the body of the tag.var
属性に指定した変数名j
をタグ内部で変数として参照することができます。
7.3.5 タグネームスペース
g:
prefix in GSP pages. However, you can specify a different namespace by adding a static property to your TagLib
class:g:
接頭辞が使用できます。ネームスペースはstaticプロパティnamespace
をTagLib
クラスに追加する事で、独自に定義することが可能です。:class SimpleTagLib { static namespace = "my"def example = { attrs -> … } }
namespace
of my
and hence the tags in this tag lib must then be referenced from GSP pages like this:namespace
をmy
と定義したので、このタグを参照するにはGSPページ内では以下のように参照できます:<my:example name="..." />
namespace
property. Namespaces are particularly useful for plugins.namespace
プロパティに設定したものが接頭辞として使用しています。ネームスペースはプラグインでタグ提供を行う際に有用です。out << my.example(name:"foo")
7.3.6 JSPタグライブラリの使用
taglib
directive:taglib
ディレクティブを定義します。<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:formatNumber value="${10}" pattern=".00"/>
${fmt.formatNumber(value:10, pattern:".00")}
7.3.7 タグの戻り値
org.codehaus.groovy.grails.web.util.StreamCharBuffer
class by default.
This change improves performance by reducing object creation and optimizing buffering during request processing.
In earlier Grails versions, a java.lang.String
instance was returned.org.codehaus.groovy.grails.web.util.StreamCharBuffer
クラスのインスタンスを返します。
この実装でリクエスト処理時のバッファリング最適化や、オブジェクト生成の減少によりパフォーマンスの向上が行われました。
それ以前のGrailsではjava.lang.String
インスタンスを返します。returnObjectForTags
property in the tag library class.returnObjectForTags
プロパティにタグ名称をリストします。class ObjectReturningTagLib { static namespace = "cms" static returnObjectForTags = ['content']def content = { attrs, body -> CmsContent.findByCode(attrs.code)?.content } }
7.4 URLマッピング
/controller/action/id
. However, this convention is not hard wired into Grails and is in fact controlled by a URL Mappings class located at grails-app/conf/UrlMappings.groovy
./controller/action/id
を使用しています。このルールはGrailsで必須になっているわけでは無く、grails-app/conf/UrlMappings.groovy
に配置されているURLマッピングクラスでコントロールされています。UrlMappings
class contains a single property called mappings
that has been assigned a block of code:URLMappings
クラスは、コードブロックが定義されたmappings
というプロパティを持っています。:class UrlMappings {
static mappings = {
}
}
7.4.1 コントローラとアクションにマッピング
"/product"(controller: "product", action: "list")
/product
to the list
action of the ProductController
. Omit the action definition to map to the default action of the controller:/product
は、ProductController
のlist
アクションにマップ定義したことになります。アクションを省略すると、コントローラのデフォルトアクションにマップ定義できます:"/product"(controller: "product")
"/product" { controller = "product" action = "list" }
If you have mappings that all fall under a particular path you can group mappings with the group
method:
group "/product", { "/apple"(controller:"product", id:"apple") "/htc"(controller:"product", id:"htc") }
"/hello"(uri: "/hello.dispatch")
7.4.2 RESTリソースへのマッピング
Since Grails 2.3, it possible to create RESTful URL mappings that map onto controllers by convention. The syntax to do so is as follows:"/books"(resources:'book')
You define a base URI and the name of the controller to map to using the resources
parameter. The above mapping will result in the following URLs:
HTTP Method | URI | Grails Action |
---|---|---|
GET | /books | index |
GET | /books/create | create |
POST | /books | save |
GET | /books/${id} | show |
GET | /books/${id}/edit | edit |
PUT | /books/${id} | update |
DELETE | /books/${id} | delete |
If you wish to include or exclude any of the generated URL mappings you can do so with the includes
or excludes
parameter, which accepts the name of the Grails action to include or exclude:
"/books"(resources:'book', excludes:['delete', 'update'])or
"/books"(resources:'book', includse:['index', 'show'])
Single resources
A single resource is a resource for which there is only one (possibly per user) in the system. You can create a single resource using the resource
parameter (as oppose to resources
):
"/book"(resource:'book')
This results in the following URL mappings:
HTTP Method | URI | Grails Action |
---|---|---|
GET | /book/create | create |
POST | /book | save |
GET | /book | show |
GET | /book/edit | edit |
PUT | /book | update |
DELETE | /book | delete |
The main difference is that the id is not included in the URL mapping.
Nested Resources
You can nest resource mappings to generate child resources. For example:
"/books"(resources:'book') { "/authors"(resources:"author") }
The above will result in the following URL mappings:
HTTP Method | URL | Grails Action |
---|---|---|
GET | /books/${bookId}/authors | index |
GET | /books/${bookId}/authors/create | create |
POST | /books/${bookId}/authors | save |
GET | /books/${bookId}/authors/${id} | show |
GET | /books/${bookId}/authors/edit/${id} | edit |
PUT | /books/${bookId}/authors/${id} | update |
DELETE | /books/${bookId}/authors/${id} | delete |
You can also nest regular URL mappings within a resource mapping:
"/books"(resources: "book") { "/publisher"(controller:"publisher") }
This will result in the following URL being available:
HTTP Method | URL | Grails Action |
---|---|---|
GET | /books/1/publisher | index |
Linking to RESTful Mappings
You can link to any URL mapping created with the g:link
tag provided by Grails simply by referencing the controller and action to link to:
<g:link controller="book" action="index">My Link</g:link>
As a convenience you can also pass a domain instance to the resource
attribute of the link
tag:
<g:link resource="${book}">My Link</g:link>
This will automatically produce the correct link (in this case "/books/1" for an id of "1").
The case of nested resources is a little different as they typically required two identifiers (the id of the resource and the one it is nested within). For example given the nested resources:
"/books"(resources:'book') { "/authors"(resources:"author") }
If you wished to link to the show
action of the author
controller, you would write:
// Results in /books/1/authors/2 <g:link controller="author" action="show" method="GET" params="[bookId:1]" id="2">The Author</g:link>
However, to make this more concise there is a resource
attribute to the link tag which can be used instead:
// Results in /books/1/authors/2 <g:link resource="book/author" action="show" bookId="1" id="2">My Link</g:link>
The resource attribute accepts a path to the resource separated by a slash (in this case "book/author"). The attributes of the tag can be used to specify the necessary bookId
parameter.
7.4.3 URLマッピングでのリダイレクト
Since Grails 2.3, it is possible to define URL mappings which specify a redirect. When a URL mapping specifies a redirect, any time that mapping matches an incoming request, a redirect is initiated with information provided by the mapping.When a URL mapping specifies a redirect the mapping must either supply a String
representing a URI to redirect to or must provide a Map representing the target
of the redirect. That Map is structured just like the Map that may be passed
as an argument to the redirect
method in a controller.
"/viewBooks"(redirect: '/books/list') "/viewAuthors"(redirect: [controller: 'author', action: 'list']) "/viewPublishers"(redirect: [controller: 'publisher', action: 'list', permanent: true])
Request parameters that were part of the original request will be included in the redirect.
7.4.4 埋込変数
簡単な変数 Simple Variables
/product
. However, in many circumstances you don't know what the value of a particular token will be until runtime. In this case you can use variable placeholders within the URL for example:/product
のように適切に指定できますが、状況によっては、ランタイム時にしか一部のトークンが予測できない場合があります。その場合は以下の例のように変数を指定できます:static mappings = { "/product/$id"(controller: "product") }
id
. For example given the URL /product/MacBook
, the following code will render "MacBook" to the response:id
のパラメータとしてマップします(このパラメータはparamsオブジェクトから取得できます)。例として、URL /product/MacBook
へアクセスを行うと、次のコードでは、結果として"MacBook"をレスポンスします:class ProductController { def index() { render params.id } }
static mappings = { "/$blog/$year/$month/$day/$id"(controller: "blog", action: "show") }
/graemerocher/2007/01/10/my_funky_blog_entry
year
, month
, day
, id
and so on. blog
, year
, month
, day
, id
として値を取得する事ができます。動的なコントローラ名とアクション名 Dynamic Controller and Action Names
static mappings = { "/$controller/$action?/$id?"() }
controller
, action
and id
embedded within the URL.controller
,action
,id
を取得して、コントローラ、アクション、idを確定します。static mappings = { "/$controller" { action = { params.goHere } } }
省略可能な変数 Optional Variables
static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }
/graemerocher/2007/01/10/my_funky_blog_entry
/graemerocher/2007/01/10
/graemerocher/2007/01
/graemerocher/2007
/graemerocher
Optional File Extensions
If you wish to capture the extension of a particular path, then a special case mapping exists:
"/$controller/$action?/$id?(.$format)?"()
By adding the (.$format)?
mapping you can access the file extension using the response.format
property in a controller:
def index() {
render "extension is ${response.format}"
}
任意変数 Arbitrary Variables
"/holiday/win" { id = "Marrakech" year = 2007 }
動的解決変数 Dynamically Resolved Variables
"/holiday/win" { id = { params.id } isEligible = { session.user != null } // must be logged in }
7.4.5 ビューへマッピング
/
to a GSP at the location grails-app/views/index.gsp
you could use:/
を、grails-app/views/index.gsp
にマッピングするには:static mappings = { "/"(view: "/index") // map the root URL }
static mappings = { "/help"(controller: "site", view: "help") // to a view for a controller }
7.4.6 レスポンスコードへマッピング
static mappings = { "403"(controller: "errors", action: "forbidden") "404"(controller: "errors", action: "notFound") "500"(controller: "errors", action: "serverError") }
static mappings = { "403"(view: "/errors/forbidden") "404"(view: "/errors/notFound") "500"(view: "/errors/serverError") }
エラーハンドリング宣言 Declarative Error Handling
static mappings = { "403"(view: "/errors/forbidden") "404"(view: "/errors/notFound") "500"(controller: "errors", action: "illegalArgument", exception: IllegalArgumentException) "500"(controller: "errors", action: "nullPointer", exception: NullPointerException) "500"(controller: "errors", action: "customException", exception: MyException) "500"(view: "/errors/serverError") }
IllegalArgumentException
will be handled by the illegalArgument
action in ErrorsController
, a NullPointerException
will be handled by the nullPointer
action, and a MyException
will be handled by the customException
action. Other exceptions will be handled by the catch-all rule and use the /errors/serverError
view.IllegalArgumentException
はErrorsControlle
rのillegalArgument
、NullPointerException
はnullPointer
アクション、MyException
はcustomException
アクションでそれぞれ処理されます。その他の例外がcatch-allルールでハンドルされビューに/errors/serverError
を使用します。exception
attribute like so:exception
を使用します:class ErrorController { def handleError() { def exception = request.exception // perform desired processing to handle the exception } }
If your error-handling controller action throws an exception as well, you'll end up with aエラーハンドリング用のコントローラアクションが例外を出した場合は、最終的にStackOverflowException
.StackOverflowException
になります。
7.4.7 HTTPメソッドへマッピング
ProductController
:ProductController
用にRESTful API URLマッピングを提供しています:static mappings = { "/product/$id"(controller:"product") { action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"] } }
7.4.8 マッピングワイルドカード
static mappings = { "/images/*.jpg"(controller: "image") }
/image/logo.jpg
. Of course you can achieve the same effect with a variable:/image/logo.jpg
のような画像パスにマッチします。変数も使用可能です:static mappings = { "/images/$name.jpg"(controller: "image") }
static mappings = { "/images/**.jpg"(controller: "image") }
/image/logo.jpg
as well as /image/other/logo.jpg
. Even better you can use a double wildcard variable:/image/logo.jpg
や、/image/other/logo.jpg
にマッチします。ダブルワイルドカード変数も使用できます:static mappings = { // will match /image/logo.jpg and /image/other/logo.jpg "/images/$name**.jpg"(controller: "image") }
name
parameter obtainable from the params object:name
パラメータにマッチしたパスをparamsオブジェクトから取得できます:def name = params.name println name // prints "logo" or "other/logo"
excludes
setting inside the UrlMappings.groovy
class:UrlMappings.groovy
クラスで、excludes
を指定することで可能です:class UrlMappings { static excludes = ["/images/*", "/css/*"] static mappings = { … } }
/images
or /css
./images
また/css
で始まるURIはURLマッピングから除外されます.
7.4.9 自動リンクリライト
static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }
<g:link controller="blog" action="show" params="[blog:'fred', year:2007]"> My Blog </g:link><g:link controller="blog" action="show" params="[blog:'fred', year:2007, month:10]"> My Blog - October 2007 Posts </g:link>
<a href="/fred/2007">My Blog</a> <a href="/fred/2007/10">My Blog - October 2007 Posts</a>
7.4.10 制約の適用
static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }
/graemerocher/2007/01/10/my_funky_blog_entry
/graemerocher/not_a_year/not_a_month/not_a_day/my_funky_blog_entry
"/$blog/$year?/$month?/$day?/$id?" { controller = "blog" action = "show" constraints { year(matches:/\d{4}/) month(matches:/\d{2}/) day(matches:/\d{2}/) } }
year
, month
and day
parameters match a particular valid pattern thus relieving you of that burden later on.year
,month
,day
パラメータが特定のパターンにマッチするように制約を定義しています。
7.4.11 名前付きURLマッピング
static mappings = {
name <mapping name>: <url pattern> {
// …
}
}
static mappings = { name personList: "/showPeople" { controller = 'person' action = 'list' } name accountDetails: "/details/$acctNumber" { controller = 'product' action = 'accountDetails' } }
<g:link mapping="personList">List People</g:link>
<a href="/showPeople">List People</a>
<g:link mapping="accountDetails" params="[acctNumber:'8675309']"> Show Account </g:link>
<a href="/details/8675309">Show Account</a>
<link:personList>List People</link:personList>
<a href="/showPeople">List People</a>
<link:accountDetails acctNumber="8675309">Show Account</link:accountDetails>
<a href="/details/8675309">Show Account</a>
href
, specify a Map
value to the attrs
attribute. These attributes will be applied directly to the href, not passed through to be used as request parameters.href
に適用されてしまうので、他の属性は、attrs
属性にMap
で指定します。<link:accountDetails attrs="[class: 'fancy']" acctNumber="8675309"> Show Account </link:accountDetails>
<a href="/details/8675309" class="fancy">Show Account</a>
7.4.12 URLフォーマットのカスタマイズ
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
.
MathHelperController
のアクションaddNumbers
の場合、デフォルトURLでのURLは、/mathHelper/addNumbers
のようになります。Grailsでは、このパターンをカスタマイズして、/math-helper/add-numbers
のようなハイフン形式にキャメルケース形式を入れ換える実装が可能です。ハイフンURLを可能にするには、grails-app/conf/Config.groovy
のgrails.web.url.converter
を"hyphenated"にします。// grails-app/conf/Config.groovygrails.web.url.converter = 'hyphenated'
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.
grails.web.UrlConverter.BEAN_NAME
で追加します。Grailsがそのビーン名称をコンテキストに有ることを認識した場合、指定したクラスの実装がデフォルトとなります。この場合は、grails.web.url.converter
プロパティは必要有りません。
// src/groovy/com/myapplication/MyUrlConverterImpl.groovypackage 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… } }
// src/groovy/com/myapplication/MyUrlConverterImpl.groovypackage com.myapplication
class MyUrlConverterImpl implements grails.web.UrlConverter {
String toUrlElement(String propertyOrClassName) { // URLで描写するプロパティ名またはクラス名を返す } }
// grails-app/conf/spring/resources.groovybeans = { "${grails.web.UrlConverter.BEAN_NAME}"(com.myapplication.MyUrlConverterImpl) }
7.4.13 コントローラネームスペース
If an application defines multiple controllers with the same name in different packages, the controllers must be defined in a namespace. The way to define a namespace for a controller is to define a static property namednamespace
in the controller and
assign a String to the property that represents the namespace.// grails-app/controllers/com/app/reporting/AdminController.groovy package com.app.reportingclass AdminController {
static namespace = 'reports'
// … }
// grails-app/controllers/com/app/security/AdminController.groovy package com.app.securityclass AdminController {
static namespace = 'users'
// … }
When defining url mappings which should be associated with a namespaced
controller, the namespace
variable needs to be part of the URL mapping.
// grails-app/conf/UrlMappings.groovy class UrlMappings {static mappings = { '/userAdmin' { controller = 'admin' namespace = 'users' }
'/reportAdmin' { controller = 'admin' namespace = 'reports' }
"/$namespace/$controller/$action?"() } }
Reverse URL mappings also require that the namespace
be specified.
<g:link controller="admin" namespace="reports">Click For Report Admin</g:link> <g:link controller="admin" namespace="users">Click For User Admin</g:link>
When resolving a URL mapping (forward or reverse) to a namespaced controller,
a mapping will only match if the namespace
has been provided. If
the application provides several controllers with the same name in different
packages, at most 1 of them may be defined without a namespace
property. If
there are multiple controllers with the same name that do not define a
namespace
property, the framework will not know how to distinguish between
them for forward or reverse mapping resolutions.
It is allowed for an application to use a plugin which provides a controller
with the same name as a controller provided by the application and for neither
of the controllers to define a namespace
property as long as the
controllers are in separate packages. For example, an application
may include a controller named com.accounting.ReportingController
and the application may use a plugin which provides a controller
named com.humanresources.ReportingController
. The only issue
with that is the URL mapping for the controller provided by the
plugin needs to be explicit in specifying that the mapping applies
to the ReportingController
which is provided by the plugin.
See the following example.
static mappings = { "/accountingReports" { controller = "reporting" } "/humanResourceReports" { controller = "reporting" plugin = "humanResources" } }
With that mapping in place, a request to /accountingReports
will
be handled by the ReportingController
which is defined in the
application. A request to /humanResourceReports
will be handled
by the ReportingController
which is provided by the humanResources
plugin.
There could be any number of ReportingController
controllers provided
by any number of plugins but no plugin may provide more than one
ReportingController
even if they are defined in separate packages.
Assigning a value to the plugin
variable in the mapping is only
required if there are multiple controllers with the same name
available at runtime provided by the application and/or plugins.
If the humanResources
plugin provides a ReportingController
and
there is no other ReportingController
available at runtime, the
following mapping would work.
static mappings = { "/humanResourceReports" { controller = "reporting" } }
It is best practice to be explicit about the fact that the controller is being provided by a plugin.
7.5 Webフロー
概要 Overview
From Grails 1.2 onwards Webflow is no longer in Grails core, so you must install the Webflow plugin to use this feature.Grails 1.2からWebフローはGrailsのコア機能では無くなりました。この機能を使用するには、Webフロープラグインをインストールする必要があります.
フローの作成 Creating a Flow
Flow
. For example:Flow
で終わるアクションをGrailsの通常にコントローラに作成します。例として:class BookController {def index() { redirect(action: "shoppingCart") }
def shoppingCartFlow = { … } }
Flow
suffix. In other words the name of the action of the above flow is shoppingCart
. Flow
を省略します。言い換えれば上記のフローのアクション名はshoppingCart
となります。
7.5.1 開始と終了のステート
class BookController { … def shoppingCartFlow ={ showCart { on("checkout").to "enterPersonalDetails" on("continueShopping").to "displayCatalogue" } … displayCatalogue { redirect(controller: "catalogue", action: "show") } displayInvoice() } }
showCart
node is the start state of the flow. Since the showCart state doesn't define an action or redirect it is assumed be a view state that, by convention, refers to the view grails-app/views/book/shoppingCart/showCart.gsp
.showCart
ノードになります。showCartがアクションまたリダイレクトを定義していない場合は、慣習によりgrails-app/views/book/shoppingCart/showCart.gsp
を参照して表示するビューステートとして見なされます。
grails-app/views/book/shoppingCart
.grails-app/views/book/shoppingCart
shoppingCart
flow also has two possible end states. The first is displayCatalogue
which performs an external redirect to another controller and action, thus exiting the flow. The second is displayInvoice
which is an end state as it has no events at all and will simply render a view called grails-app/views/book/shoppingCart/displayInvoice.gsp
whilst ending the flow at the same time. shoppingCart
フローには、2つの終了ステートがあります。一つ目のステートは、外部のコントローラアクションにリダイレクトしてフローから出るdisplayCatalogue
。二つ目のステートは、何もイベント処理が無く単純に、ビューのgrails-app/views/book/shoppingCart/displayInvoice.gsp
を描写して同時にフローを終了する、displayInvoice
です。showCart
, and not from any other state.showCart
になります。
7.5.2 アクションステートとビューステート
ビューステート View states
action
or a redirect
. So for example this is a view state:action
またridairect
を定義していないものがビューステートです。この例がビューステートになります:enterPersonalDetails { on("submit").to "enterShipping" on("return").to "showCart" }
grails-app/views/book/shoppingCart/enterPersonalDetails.gsp
by default. Note that the enterPersonalDetails
state defines two events: submit
and return
. The view is responsible for triggering these events. Use the render
method to change the view to be rendered:
grails-app/views/book/shoppingCart/enterPersonalDetails.gsp
を使用します。enterPersonalDetails
ステートは、submit
とreturn
という2つのイベントを定義しています。これらのイベントはビューでトリガーする必要があります。render
メソッドを使用して描写するビューを変更することが可能です:enterPersonalDetails { render(view: "enterDetailsView") on("submit").to "enterShipping" on("return").to "showCart" }
grails-app/views/book/shoppingCart/enterDetailsView.gsp
. Start the view
parameter with a / to use a shared view:grails-app/views/book/shoppingCart/enterDetailsView.gsp
を参照するようになります。view
のパラメータに / を使用して共有ビューを使用できます:enterPersonalDetails { render(view: "/shared/enterDetailsView") on("submit").to "enterShipping" on("return").to "showCart" }
grails-app/views/shared/enterDetailsView.gsp
grails-app/views/shared/enterDetailsView.gsp
を参照するようになります。アクションステート Action States
action
method and passing it a block of code to be executed:action
メソッドに実行したいコードブロックを渡してアクションステートを実装します:listBooks { action { [bookList: Book.list()] } on("success").to "showCatalogue" on(Exception).to "handleError" }
success
event will be triggered. In this case since we return a Map, which is regarded as the "model" and is automatically placed in flow scope.success
イベントがトリガーされます。この例では、モデルと見なしたMapを返して自動的にflowスコープに配置されます。on(Exception).to "handleError"
handleError
in the case of an exception.handleError
というステートにフローが移行します。processPurchaseOrder { action { def a = flow.address def p = flow.person def pd = flow.paymentDetails def cartItems = flow.cartItems flow.clear()def o = new Order(person: p, shippingAddress: a, paymentDetails: pd) o.invoiceNumber = new Random().nextInt(9999999) for (item in cartItems) { o.addToItems item } o.save() [order: o] } on("error").to "confirmPurchase" on(Exception).to "confirmPurchase" on("success").to "displayInvoice" }
Order
object. It then returns the order as the model. The important thing to note here is the interaction with the request context and "flow scope".Order
オブジェクトを生成しています。そして生成後オーダーをモデルで返しています。ここで重要なのはリクエストコンテキストと"flowスコープ"のやりとりです。アクションのトランジション Transition Actions
enterPersonalDetails { on("submit") { log.trace "Going to enter shipping" }.to "enterShipping" on("return").to "showCart" }
submit
event that simply logs the transition. Transition states are very useful for data binding and validation, which is covered in a later section.submit
イベントにコードブロックを渡してトランジションのログを実行しています。この後に解説をする、データバインディングとバリデーションで、このトランジションステートが便利に活用できます。
7.5.3 フロー実行イベント
ビューステートからのイベントトリガー Triggering Events from a View State
checkout
event and a continueShopping
event:checkout
イベントとcontinueShopping
イベントです:def shoppingCartFlow = { showCart { on("checkout").to "enterPersonalDetails" on("continueShopping").to "displayCatalogue" } … }
showCart
event is a view state it will render the view grails-app/book/shoppingCart/showCart.gsp
. Within this view you need to have components that trigger flow execution. On a form this can be done use the submitButton tag:shopCart
イベントはビューステートなので、grails-app/book/shoppingCart/showCart.gsp
を描写します。このビューの中に、フロートリガーを実行するコンポーネントを持つ必要があります。 submitButtonタグを使用したフォームを使います:<g:form> <g:submitButton name="continueShopping" value="Continue Shopping" /> <g:submitButton name="checkout" value="Checkout" /> </g:form>
shoppingCart
flow. The name attribute of each submitButton tag signals which event will be triggered. If you don't have a form you can also trigger an event with the link tag as follows:shoppingCart
フローへ送信します。それぞれのsubmitButtonタグのname属性にトリガーするイベントを指定します。フォームを使用しない場合は、次のようにlinkタグをイベントトリガーに使用できます:<g:link event="checkout" />
Prior to 2.0.0, it was required to specify the controller and/or action in forms and links, which caused the url to change when entering a subflow state. When the controller and action are not specified, all url's are relative to the main flow execution url, which makes your flows reusable as subflows and prevents issues with the browser's back button.
アクションからのイベントトリガー Triggering Events from an Action
action
you invoke a method. For example there is the built in error()
and success()
methods. The example below triggers the error()
event on validation failure in a transition action:error()
とsuccess()
メソッド(トランジションアクション)が有るのでそれを例に使用します。次の例では、トランジションアクションでバリデーションが失敗したらerror()
イベントをトリガーしています:enterPersonalDetails { on("submit") { def p = new Person(params) flow.person = p if (!p.validate()) return error() }.to "enterShipping" on("return").to "showCart" }
enterPersonalDetails
state.enterPersonalDetails
ステートに戻ります。shippingNeeded { action { if (params.shippingRequired) yes() else no() } on("yes").to "enterShipping" on("no").to "enterPayment" }
7.5.4 フローのスコープ
スコープの基礎 Scope Basics
flow
to store objects within "flow scope". Grails flows have five different scopes you can utilize:flow
という特殊なオブジェクトを使用しました。Grailsフローでは5つのスコープが利用できます:request
- Stores an object for the scope of the current requestflash
- Stores the object for the current and next request onlyflow
- Stores objects for the scope of the flow, removing them when the flow reaches an end stateconversation
- Stores objects for the scope of the conversation including the root flow and nested subflowssession
- Stores objects in the user's session
- request - 現在のリクエスト範囲のオブジェクトを蓄積
- flash - 現在と次までが有効範囲のオブジェクトを蓄積
- flow - フロー範囲で有効なオブジェクトを蓄積。フローが終了ステートに到達したら削除されます。
- conversation - ルートフローやサブフローを含む範囲での対話でのオブジェクトを蓄積
- session - ユーザのセッションへオブジェクトを蓄積
Grails service classes can be automatically scoped to a web flow scope. See the documentation on Services for more information.Grailsサービスクラスは自動的にflowスコープになります。詳しくはサービスを参照してください。
flow
scope as follows:flow
スコープにオブジェクトを配置できます:enterPersonalDetails { on("submit") { [person: new Person(params)] }.to "enterShipping" on("return").to "showCart" }
- Moves objects from flash scope to request scope upon transition between states;
- Merges objects from the flow and conversation scopes into the view model before rendering (so you shouldn't include a scope prefix when referencing these objects within a view, e.g. GSP pages).
- ステート間のトランジションでオブジェクトをflashスコープからrequestスコープへ移動します。
- 描写する前に、flowとconversationスコープのオブジェクトをビューモデルにマージします。(GSPページ等のビューでオブジェクトを参照する際はスコープ接頭辞を含まないでください)
フロースコープとシリアライズ Flow Scopes and Serialization
flash
, flow
or conversation
scope they must implement java.io.Serializable
or an exception will be thrown. This has an impact on domain classes in that domain classes are typically placed within a scope so that they can be rendered in a view. For example consider the following domain class:flash
、flow
またconversation
スコープに配置するオブジェクトは、必ずjava.io.Serializable
を継承してください。継承しない場合は例外を投げます。ドメインクラスは通常スコープに配置されビューの描写に使用するので影響を受けます。例として次のようなドメインクラスがあるとします:class Book {
String title
}
Book
class in a flow scope you will need to modify it as follows:Book
のインスタンスをflowスコープで使用する場合は次のようにします:class Book implements Serializable { String title }
class Book implements Serializable { String title Author author }
Author
association is not Serializable
you will also get an error. This also impacts closures used in GORM events such as onLoad
, onSave
and so on. The following domain class will cause an error if an instance is placed in a flow scope:Author
がSerializable
では無い場合はエラーとなります。onLoad
やonSave
等のGORMイベントのクロージャにも影響があります。次のドメインクラスをflowスコープに配置するとエラーとなります:class Book implements Serializable {String title
def onLoad = { println "I'm loading" } }
onLoad
event cannot be serialized. To get around this you should declare all events as transient
:onLoad
イベントのブロックがシリアライズされないからです。これを対応させるにはイベントにtransient
を指定します:class Book implements Serializable {String title
transient onLoad = { println "I'm loading" } }
class Book implements Serializable {String title
def onLoad() { println "I'm loading" } }
The flow scope contains a reference to the Hibernate session. As a result, any object loaded into the session through a GORM query will also be in the flow and will need to implement Serializable.If you don't want your domain class to be Serializable or stored in the flow, then you will need to evict the entity manually before the end of the state:
flow.persistenceContext.evict(it)
7.5.5 データバインディングとバリデーション
enterPersonalDetails
state. This state renders a view and waits for the user to enter the required information:enterPersonalDetails
ステートへトリガーしています。このステートはビューを描写して、ユーザが必要な情報をエントリーするのを待ちます:enterPersonalDetails { on("submit").to "enterShipping" on("return").to "showCart" }
<g:form> <!-- Other fields --> <g:submitButton name="submit" value="Continue"></g:submitButton> <g:submitButton name="return" value="Back"></g:submitButton> </g:form>
enterPersonalDetails { on("submit") { flow.person = new Person(params) !flow.person.validate() ? error() : success() }.to "enterShipping" on("return").to "showCart" }
Person
instance within flow
scope. Also interesting is that we perform validation and invoke the error()
method if validation fails. This signals to the flow that the transition should halt and return to the enterPersonalDetails
view so valid entries can be entered by the user, otherwise the transition should continue and go to the enterShipping
state.flow
スコープのPerson
インスタンスに渡している部分を注目してください。さらに興味深い部分は、バリデーションを実行して、失敗したらerror()
メソッドを実行している部分です。この結果を受け取るとトランジションは停止されenterPersonalDetails
ビューへ戻りユーザが正当な内容をエントリできるようになります。あるいは内容が問題無ければ、トランジションが続行されてenterShipping
ステートへ移動します。enterPersonalDetails { on("submit") { PersonDetailsCommand cmd -> flow.personDetails = cmd !flow.personDetails.validate() ? error() : success() }.to "enterShipping" on("return").to "showCart" }
7.5.6 サブフローとの対話
def searchFlow = { displaySearchForm { on("submit").to "executeSearch" } executeSearch { action { [results:searchService.executeSearch(params.q)] } on("success").to "displayResults" on("error").to "displaySearchForm" } displayResults { on("searchDeeper").to "extendedSearch" on("searchAgain").to "displaySearchForm" } extendedSearch { // Extended search subflow subflow(controller: "searchExtensions", action: "extendedSearch") on("moreResults").to "displayMoreResults" on("noResults").to "displayNoMoreResults" } displayMoreResults() displayNoMoreResults() }
extendedSearch
state. The controller parameter is optional if the subflow is defined in the same controller as the calling flow.extendedSearch
ステートで中にサブフローを参照しています。サブフローが同じコントローラで呼ばれる場合は、コントローラを指定するパラメータは省略可能です。Prior to 1.3.5, the previous subflow call would look like1.3.5以前、サブフローは、subflow(new SearchExtensionsController().extendedSearchFlow)
, with the requirement that the name of the subflow state be the same as the called subflow (minusFlow
). This way of calling a subflow is deprecated and only supported for backward compatibility.subflow(new SearchExtensionsController().extendedSearchFlow)
のように呼び出しました。この方法は非推奨となっており、下位互換のために対応はしています。
def extendedSearchFlow = { startExtendedSearch { on("findMore").to "searchMore" on("searchAgain").to "noResults" } searchMore { action { def results = searchService.deepSearch(ctx.conversation.query) if (!results) return error() conversation.extendedResults = results } on("success").to "moreResults" on("error").to "noResults" } moreResults() noResults() }
Notice how it places the extendedResults
in conversation scope. This scope differs to flow scope as it lets you share state that spans the whole conversation, i.e. a flow execution including all subflows, not just the flow itself. Also notice that the end state (either moreResults
or noResults
of the subflow triggers the events in the main flow:
extendedSearch { // Extended search subflow subflow(controller: "searchExtensions", action: "extendedSearch") on("moreResults").to "displayMoreResults" on("noResults").to "displayNoMoreResults" }
Subflow input and output
Using conversation scope for passing input and output between flows can be compared with using global variables to pass information between methods. While this is OK in certain situations, it is usually better to use method arguments and return values. In webflow speak, this means defining input and output arguments for flows.Consider following flow for searching a person with a certain expertise:
def searchFlow = { input { expertise(required: true) title("Search person") }search { onEntry { [personInstanceList: Person.findAllByExpertise(flow.expertise)] } on("select") { flow.person = Person.get(params.id) }.to("selected") on("cancel").to("cancel") }
selected { output { person {flow.person} } } cancel() }
}
This flow accepts two input parameters:
- a required expertise argument
- an optional title argument with a default value
All input arguments are stored in flow scope and are, just like local variables, only visible within this flow.
A flow that contains required input will throw an exception when an execution is started without providing the input. The consequence is that these flows can only be started as subflows.
Notice how an end state can define one or more named output values. If the value is a closure, this closure will be evaluated at the end of each flow execution. If the value is not a closure, the value will be a constant that is only calculated once at flow definition time.
When a subflow is called, we can provide it a map with input values:
def newProjectWizardFlow = { ...managerSearch { subflow(controller: "person", action: "search", input: [expertise : "management", title: "Search project manager"]) on("selected") { flow.projectInstance.manager = currentEvent.attributes.person }.to "techleadSearch" }
techleadSearch { subflow(controller: "person", action: "search", input: [expertise : { flow.technology }, title: "Search technical lead"]) on("selected") { flow.projectInstance.techlead = currentEvent.attributes.person }.to "projectDetails" }
...
}
Notice again the difference between constant values like expertise : "management"
and dynamic values like expertise : { flow.technology }
The subflow output is available via currentEvent.attributes
7.6 フィルタ
7.6.1 フィルタの適用
Filters
in the grails-app/conf
directory. Within this class define a code block called filters
that contains the filter definitions:grails-app/conf
ディレクトリに、名称がFilters
で終わるクラスを作成します。このクラスにはフィルタを記述する、filters
というコードブロックを定義します:class ExampleFilters { def filters = { // your filters here } }
filters
block has a name and a scope. The name is the method name and the scope is defined using named arguments. For example to define a filter that applies to all controllers and all actions you can use wildcards:filters
ブロックに定義する各フィルタには、範囲と名称を持たせます。名称はメソッド名で、範囲は引数で定義します。例として、ワイルドカードを使用した全コントローラ・アクションに適用されるフィルタを定義します:sampleFilter(controller:'*', action:'*') { // interceptor definitions }
- A controller and/or action name pairing with optional wildcards
- A URI, with Ant path matching syntax
- 省略可能なワイルドカードを使用した、コントローラ名と(または)アクション名の組み合わせ。
- Antパスマッチング書式のURI指定。
controller
- controller matching pattern, by default * is replaced with .* and a regex is compiledcontrollerExclude
- controller exclusion pattern, by default * is replaced with .* and a regex is compiledaction
- action matching pattern, by default * is replaced with .* and a regex is compiledactionExclude
- action exclusion pattern, by default * is replaced with .* and a regex is compiledregex
(true
/false
) - use regex syntax (don't replace '*' with '.*')uri
- a uri to match, expressed with as Ant style path (e.g. /book/**)uriExclude
- a uri pattern to exclude, expressed with as Ant style path (e.g. /book/**)find
(true
/false
) - rule matches with partial match (seejava.util.regex.Matcher.find()
)invert
(true
/false
) - invert the rule (NOT rule)
controller
- コントローラ対象のパターンマッチング, 既存値 * で正規表現コンパイル時には .*に置換されます。controllerExclude
- 除外するコントローラのパターン, 既存値 * で正規表現コンパイル時には .*に置換されます。action
- アクション対象のパターンマッチング, 既存値 * で正規表現コンパイル時には .*に置換されます。actionExclude
- 除外するアクションのパターン, 既存値 * で正規表現コンパイル時には .*に置換されます。regex (true/false)
- 正規表現の使用 ('*' を '.*'に置換しない指定)uri
- URIマッチ, Antスタイルパス (e.g. /book/**)uriExclude
- 除外するURIパターン, Antスタイルパス (e.g. /book/**)find (true/false)
- 部分マッチ (java.util.regex.Matcher.find()
を参照)invert (true/false)
- ルールを逆にする
- All controllers and actions
- 全てのコントローラとアクション
all(controller: '*', action: '*') {}
- Only for the
BookController
BookController
のみ
justBook(controller: 'book', action: '*') {}
- All controllers except the
BookController
BookController
以外の全て
notBook(controller: 'book', invert: true) {}
- All actions containing 'save' in the action name
- 'save'を名称に含めたアクション全て
saveInActionName(action: '*save*', find: true) {}
- All actions starting with the letter 'b' except for actions beginning with the phrase 'bad*'
- "bad*"を除外した、'b'で始まるアクション全て
actionBeginningWithBButNotBad(action: 'b*', actionExclude: 'bad*', find: true) {}
- Applied to a URI space
- URIへ適用
someURIs(uri: '/book/**') {}
- Applied to all URIs
- 全てのURIに適用
allURIs(uri: '/**') {}
filters
code block dictates the order in which they are executed. To control the order of execution between Filters
classes, you can use the dependsOn
property discussed in filter dependencies section.filters
コードブロックに定義した順序でフィルタは実行されます。Filters
クラス間での実行を制御するには、フィルタ依存セクションで記載されているdependsOn
プロパティが使用できます。Note: When exclude patterns are used they take precedence over the matching patterns. For example, if action is 'b*' and actionExclude is 'bad*' then actions like 'best' and 'bien' will have that filter applied but actions like 'bad' and 'badlands' will not.注意:除外パターンが使用された場合は除外マッチングパターンが優先されます。例として、アクションが'b*' で、actionExcludeが'bad*'の場合、'best','bien'等のアクションは適用されますが、'bad','badland'は適用されません。
7.6.2 フィルタの種類
before
- Executed before the action. Returnfalse
to indicate that the response has been handled that that all future filters and the action should not executeafter
- Executed after an action. Takes a first argument as the view model to allow modification of the model before rendering the viewafterView
- Executed after view rendering. Takes an Exception as an argument which will be non-null
if an exception occurs during processing. Note: this Closure is called before the layout is applied.
before
- アクションの前に実行されます。false
を返す事で、その後に実行されるフィルタとアクションは実行されません。after
- アクションの後に実行されます。最初の引数に、ビュー描写前に変更可能なビューモデルが渡されます。afterView
- ビュー描写後に実行されます。実行時に例外が発生した場合はnon-null
なExceptionが引数として渡されます。このクロージャはレイアウトが適用される前に実行されます。
class SecurityFilters { def filters = { loginCheck(controller: '*', action: '*') { before = { if (!session.user && !actionName.equals('login')) { redirect(action: 'login') return false } } } } }
loginCheck
filter uses a before
interceptor to execute a block of code that checks if a user is in the session and if not redirects to the login action. Note how returning false ensure that the action itself is not executed.loginCheck
フィルタは、before
インターセプタのコードブロックを実行することで、ユーザがセッションに無い場合はloginアクションへリダイレクトしています。falseを返す事で対象のアクション自身が実行されないようにします。Here's a more involved example that demonstrates all three filter types:
import java.util.concurrent.atomic.AtomicLongclass LoggingFilters {
private static final AtomicLong REQUEST_NUMBER_COUNTER = new AtomicLong() private static final String START_TIME_ATTRIBUTE = 'Controller__START_TIME__' private static final String REQUEST_NUMBER_ATTRIBUTE = 'Controller__REQUEST_NUMBER__'
def filters = {
logFilter(controller: '*', action: '*') {
before = { if (!log.debugEnabled) return true
long start = System.currentTimeMillis() long currentRequestNumber = REQUEST_NUMBER_COUNTER.incrementAndGet()
request[START_TIME_ATTRIBUTE] = start request[REQUEST_NUMBER_ATTRIBUTE] = currentRequestNumber
log.debug "preHandle request #$currentRequestNumber : " + "'$request.servletPath'/'$request.forwardURI', " + "from $request.remoteHost ($request.remoteAddr) " + " at ${new Date()}, Ajax: $request.xhr, controller: $controllerName, " + "action: $actionName, params: ${new TreeMap(params)}"
return true }
after = { Map model ->
if (!log.debugEnabled) return true
long start = request[START_TIME_ATTRIBUTE] long end = System.currentTimeMillis() long requestNumber = request[REQUEST_NUMBER_ATTRIBUTE]
def msg = "postHandle request #$requestNumber: end ${new Date()}, " + "controller total time ${end - start}ms" if (log.traceEnabled) { log.trace msg + "; model: $model" } else { log.debug msg } }
afterView = { Exception e ->
if (!log.debugEnabled) return true
long start = request[START_TIME_ATTRIBUTE] long end = System.currentTimeMillis() long requestNumber = request[REQUEST_NUMBER_ATTRIBUTE]
def msg = "afterCompletion request #$requestNumber: " + "end ${new Date()}, total time ${end - start}ms" if (e) { log.debug "$msg \n\texception: $e.message", e } else { log.debug msg } } } } }
In this logging example we just log various request information, but note that the model
map in the after
filter is mutable. If you need to add or remove items from the model map you can do that in the after
filter.
7.6.3 変数とスコープ
- request - The HttpServletRequest object
- response - The HttpServletResponse object
- session - The HttpSession object
- servletContext - The ServletContext object
- flash - The flash object
- params - The request parameters object
- actionName - The action name that is being dispatched to
- controllerName - The controller name that is being dispatched to
- grailsApplication - The Grails application currently running
- applicationContext - The ApplicationContext object
- request - HttpServletRequestオブジェクト
- response - HttpServletResponseオブジェクト
- session - HttpSessionオブジェクト
- servletContext - ServletContextオブジェクト
- flash - flashオブジェクト
- params - リクエストパラメータオブジェクト
- actionName - ディスパッチ対象のアクション名
- controllerName - ディスパッチ対象のコントローラ名
- grailsApplication - 起動中のGrailsアプリケーション
- applicationContext - ApplicationContextオブジェクト
7.6.4 フィルタ依存関係
Filters
class, you can specify any other Filters
classes that should first be executed using the dependsOn
property. This is used when a Filters
class depends on the behavior of another Filters
class (e.g. setting up the environment, modifying the request/session, etc.) and is defined as an array of Filters
classes.Filters
クラスでは、dependsOn
プロパティに他のFilters
クラスを定義して先に実行させることが可能です。この機能はFilters
クラスが他のFilters
クラスの振る舞いに依存する場合等に使用します。Filters
classes:Filters
クラスの例を見ていきましょう:class MyFilters { def dependsOn = [MyOtherFilters]def filters = { checkAwesome(uri: "/*") { before = { if (request.isAwesome) { // do something awesome } } }
checkAwesome2(uri: "/*") { before = { if (request.isAwesome) { // do something else awesome } } } } }
class MyOtherFilters { def filters = { makeAwesome(uri: "/*") { before = { request.isAwesome = true } } doNothing(uri: "/*") { before = { // do nothing } } } }
dependsOn
MyOtherFilters. This will cause all the filters in MyOtherFilters whose scope matches the current request to be executed before those in MyFilters. For a request of "/test", which will match the scope of every filter in the example, the execution order would be as follows:dependsOn
にMyOtherFiltersを指定しています。これにより、リクエストがフィルタ範囲にマッチしたMyOtherFiltersのフィルタがMyFiltersの前に実行されます。この例では"/test"とリクエストした場合全てのフィルタにマッチします。フィルタ実行順は次のようになります:
- MyOtherFilters - makeAwesome
- MyOtherFilters - doNothing
- MyFilters - checkAwesome
- MyFilters - checkAwesome2
Filters
classes are enabled and the execution order of filters within each Filters
class are preserved.Filters
クラスの実行順が可能になり、各Filters
クラスのフィルタ実行順も保っています。org.codehaus.groovy.grails.plugins.web.filters.FiltersGrailsPlugin
) when debugging filter dependency issues.7.7 Ajax
Note: JavaScript examples use the jQuery library.
7.7.1 Ajax対応
<head>
tag of your page:<head>
タグ内に以下を追加します:<g:javascript library="jquery" />
jQuery
with any other library supplied by a plugin you have installed. This works because of Grails' support for adaptive tag libraries. Thanks to Grails' plugin system there is support for a number of different Ajax libraries including (but not limited to):jquery
の部分を入れ換えます。これはGrailsの適用性のあるタグライブラリで可能にしています。Grailsのプラグインには、次の様々なAjaxライブラリが存在します(これは一部です):
- jQuery
- Prototype
- Dojo
- YUI
- MooTools
7.7.1.1 リモートリンク
<g:remoteLink action="delete" id="1">Delete Book</g:remoteLink>
delete
action of the current controller with an id of 1
.delete
アクションに非同期リクエストを送信します。
7.7.1.2 コンテンツの更新
def delete() {
def b = Book.get(params.id)
b.delete()
render "Book ${b.id} was deleted"
}
<div id="message"></div> <g:remoteLink action="delete" id="1" update="message"> Delete Book </g:remoteLink>
message
div
to the response in this case "Book 1 was deleted"
. This is done by the update
attribute on the tag, which can also take a Map to indicate what should be updated on failure:messege
のidをもったdiv
エレメントの内容を"Book 1 was deleted"
に更新します。この更新動作は、タグのupdate
属性で対象を指定しています。さらにMapを使用して更新失敗時の表示先も指定できます:
<div id="message"></div> <div id="error"></div> <g:remoteLink update="[success: 'message', failure: 'error']" action="delete" id="1"> Delete Book </g:remoteLink>
error
div will be updated if the request failed.error
のIDをもつdivタグ内が更新されます。
7.7.1.3 リモートフォーム送信
<g:formRemote url="[controller: 'book', action: 'delete']" update="[success: 'message', failure: 'error']"> <input type="hidden" name="id" value="1" /> <input type="submit" value="Delete Book!" /> </g:formRemote >
<form action="delete"> <input type="hidden" name="id" value="1" /> <g:submitToRemote action="delete" update="[success: 'message', failure: 'error']" /> </form>
7.7.1.4 Ajaxイベント
<g:remoteLink action="show" id="1" update="success" onLoading="showProgress()" onComplete="hideProgress()">Show Book 1</g:remoteLink>
onSuccess
- The JavaScript function to call if successfulonFailure
- The JavaScript function to call if the call failedon_ERROR_CODE
- The JavaScript function to call to handle specified error codes (eg on404="alert('not found!')")onUninitialized
- The JavaScript function to call the a Ajax engine failed to initialiseonLoading
- The JavaScript function to call when the remote function is loading the responseonLoaded
- The JavaScript function to call when the remote function is completed loading the responseonComplete
- The JavaScript function to call when the remote function is complete, including any updates
onSuccess
- 成功した時に呼び出すJavaScriptファンクションonFailure
- 失敗した時に呼び出すJavaScriptファンクションon_ERROR_CODE
- 指定したエラーコードを取得したら呼び出すJavaScriptファンクション (eg on404="alert('not found!')")onUninitialized
- Ajaxエンジンの初期化に失敗したときに呼び出すJavaScriptファンクションonLoading
- レスポンスを読み込み中に呼び出すJavaScriptファンクションonLoaded
- レスポンスの読み込み完了時に呼び出すJavaScriptファンクションonComplete
- リモートファンクションが完全に完了(更新を含む)したら呼び出すJavaScriptファンクション
XMLHttpRequest
variable to obtain the request:XMLHttpRequest
変数で参照できます:<g:javascript> function fireMe(event) { alert("XmlHttpRequest = " + event) } } </g:javascript> <g:remoteLink action="example" update="success" onFailure="fireMe(XMLHttpRequest)">Ajax Link</g:remoteLink>
7.7.2 Prototypeを使用したAjax
runtime ":prototype:latest.release"
<g:javascript library="prototype" />
<g:javascript library="scriptaculous" />
7.7.3 Dojoを使用したAjax
compile ":dojo:latest.release"
<g:javascript library="dojo" />
7.7.4 GWTを使用したAjax
7.7.5 Ajax使用時のサーバサイド
- Content Centric Ajax - Where you just use the HTML result of a remote call to update the page
- Data Centric Ajax - Where you actually send an XML or JSON response from the server and programmatically update the page
- Script Centric Ajax - Where the server sends down a stream of JavaScript to be evaluated on the fly
- コンテント中心なAjax - リモートコールの結果HTMLページを更新する。
- データ中心なAjax - XMLまたはJSONをサーバから送信してページをプログラムで更新する。
- スクリプトを使用したAjax - サーバからJavascriptを送信して実行させる。
コンテント中心のAjax Content Centric Ajax
def showBook() { def b = Book.get(params.id)render(template: "bookTemplate", model: [book: b]) }
<g:remoteLink action="showBook" id="${book.id}" update="book${book.id}">Update Book</g:remoteLink><div id="book${book.id}"> <!--existing book mark-up --> </div>
JSONを使用したデータ中心のAjax Data Centric Ajax with JSON
import grails.converters.JSONdef showBook() { def b = Book.get(params.id)
render b as JSON }
<g:javascript> function updateBook(data) { $("#book" + data.id + "_title").html( data.title ); } </g:javascript> <g:remoteLink action="showBook" id="${book.id}" onSuccess="updateBook(data)"> Update Book </g:remoteLink> <g:set var="bookId">book${book.id}</g:set> <div id="${bookId}"> <div id="${bookId}_title">The Stand</div> </div>
XMLを使用したデータ中心のAjax Data Centric Ajax with XML
import grails.converters.XMLdef showBook() { def b = Book.get(params.id)
render b as XML }
<g:javascript> function updateBook(data) { var id = $(data).find("book").attr("id"); $("#book" + id + "_title").html( $(data).find("title").text() ); } <g:javascript> <g:remoteLink action="test" update="foo" onSuccess="updateBook(e)"> Update Book </g:remoteLink> <g:set var="bookId">book${book.id}</g:set> <div id="${bookId}"> <div id="${bookId}_title">The Stand</div> </div>
スクリプトを使用したAjax Script Centric Ajax with JavaScript
def showBook() { def b = Book.get(params.id)response.contentType = "text/javascript" String title = b.title.encodeAsJavaScript() render "$('#book${b.id}_title').html('${title}');" }
contentType
to text/javascript
. If you use Prototype on the client the returned JavaScript will automatically be evaluated due to this contentType
setting.contentType
をtext/javascript
にすることを思えて起きましょう。Prototypeを使用した場合はこのcontentType
で自動的にJavaScriptを評価します。AjaxとAjaxでない両方へのレスポンス Responding to both Ajax and non-Ajax requests
isXhr()
method to HttpServletRequest
which can be used to identify Ajax requests. For example you could render a page fragment using a template for Ajax requests or the full page for regular HTTP requests:HttpServletRequest
にisXhr()
メソッドを追加しています。例として、Ajaxリクエストの場合はテンプレートでページの一部を描写し、それ以外は全ページ描写を行う場合:def listBooks() { def books = Book.list(params) if (request.xhr) { render template: "bookTable", model: [books: books] } else { render view: "list", model: [books: books] } }
7.8 コンテントネゴシエーション
Accept
header, an explicit format request parameter or the extension of a mapped URI.Accept
ヘッダーまたはマップされたURIの拡張子でのコンテントネゴシエーションに対応しています。Mimeタイプの定義 Configuring Mime Types
grails-app/conf/Config.groovy
using the grails.mime.types
setting: grails-app/conf/Config.groovy
のgrails.mime.types
設定に幾つかのコンテントタイプがデフォルトで定義されています:grails.mime.types = [ all: '*/*', atom: 'application/atom+xml', css: 'text/css', csv: 'text/csv', form: 'application/x-www-form-urlencoded', html: ['text/html','application/xhtml+xml'], js: 'text/javascript', json: ['application/json', 'text/json'], multipartForm: 'multipart/form-data', rss: 'application/rss+xml', text: 'text/plain', hal: ['application/hal+json','application/hal+xml'], xml: ['text/xml', 'application/xml'] ]
Content Negotiation using the format parameter
Let's say a controller action can return a resource in a variety of formats: HTML, XML, and JSON. What format will the client get? The easiest and most reliable way for the client to control this is through a format
URL parameter.
So if you, as a browser or some other client, want a resource as XML, you can use a URL like this:
http://my.domain.org/books?format=xml
The result of this on the server side is a format
property on the response
object with the value xml
. You could code your controller action to return XML based on this property, but you can also make use of the controller-specific withFormat()
method:
import grails.converters.JSON import grails.converters.XMLclass BookController {
def list() { def books = Book.list()
withFormat { html bookList: books json { render books as JSON } xml { render books as XML } } } }
In this example, Grails will only execute the block inside withFormat()
that matches the requested content type. So if the preferred format is html
then Grails will execute the html()
call only. Each 'block' can either be a map model for the corresponding view (as we are doing for 'html' in the above example) or a closure. The closure can contain any standard action code, for example it can return a model or render content directly.
There is a special format, "all", that is handled differently from the explicit formats. If "all" is specified (normally this happens through the Accept header - see below), then the first block of withFormat()
is executed. You should not add an explicit "all" block. In the above example, a format of "all" will trigger the html
handler.
When using withFormat make sure it is the last call in your controller action as the return value of the withFormat
method is used by the action to dictate what happens next.
Acceptヘッダーを使用する Using the Accept header
Every incoming HTTP request has a special Accept header that defines what media types (or mime types) a client can "accept". In older browsers this is typically:
*/*
which simply means anything. However, newer browsers send more interesting values such as this one sent by Firefox:
text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png, */*;q=0.5
This particular accept header is unhelpful because it indicates that XML is the preferred response format whereas the user is really expecting HTML. That's why Grails ignores the accept header by default for browsers. However, non-browser clients are typically more specific in their requirements and can send accept headers such as
application/json
As mentioned the default configuration in Grails is to ignore the accept header for browsers. This is done by the configuration setting grails.mime.disable.accept.header.userAgents
, which is configured to detect the major rendering engines and ignore their ACCEPT headers. This allows Grails' content negotiation to continue to work for non-browser clients:
grails.mime.disable.accept.header.userAgents = ['Gecko', 'WebKit', 'Presto', 'Trident']
For example, if it sees the accept header above ('application/json') it will set format
to json
as you'd expect. And of course this works with the withFormat()
method in just the same way as when the format
URL parameter is set (although the URL parameter takes precedence).
An accept header of '*/*' results in a value of all
for the format
property.
リクエストフォーマット vs レスポンスフォーマット Request format vs. Response format
CONTENT_TYPE
header and is typically used to detect if the incoming request can be parsed into XML or JSON, whilst the response format uses the file extension, format parameter or ACCEPT header to attempt to deliver an appropriate response to the client.CONTENT_TYPE
ヘッダの指定で入ってくるリクエストを認識してXMLまたJSON等に分類します。レスポンスフォーマットでは、ファイル拡張子、フォーマットパラメータまたはACCEPTヘッダを認識して適したレスポンスをクライアントに返します。withFormat
method available on the request:withFormat
メソッドを使用します:request.withFormat { xml { // read XML } json { // read JSON } }
リクエストパラメータformatでのコンテントネゴシエーション Content Negotiation with the format Request Parameter
format
request parameter:format
が使用できます:/book/list?format=xml
"/book/list"(controller:"book", action:"list") { format = "xml" }
URI拡張子でのコンテントネゴシエーション Content Negotiation with URI Extensions
/book/list.xml
This works as a result of the default URL Mapping definition which is:
"/$controller/$action?/$id?(.${format})?"{
Note the inclusion of the format
variable in the path. If you do not wish to use content negotiation via the file extension then simply remove this part of the URL mapping:
"/$controller/$action?/$id?"{
コンテントネゴシエーションをテスト Testing Content Negotiation
void testJavascriptOutput() { def controller = new TestController() controller.request.addHeader "Accept", "text/javascript, text/html, application/xml, text/xml, */*"controller.testAction() assertEquals "alert('hello')", controller.response.contentAsString }
void testJavascriptOutput() { def controller = new TestController() controller.params.format = 'js'controller.testAction() assertEquals "alert('hello')", controller.response.contentAsString }
8 Webサービス
8.1 REST
Grails includes flexible features that make it easy to create RESTful APIs. Creating a RESTful resource can be as simple as one line of code, as demonstrated in the next section.
8.1.1 RESTリソースとしてドメインクラスを使用する
grails.rest.Resource
transformation to any domain class:
grails.rest.Resource
変換を追加するだけです:import grails.rest.*@Resource(uri='/books') class Book {
String title
static constraints = { title blank:false } }
Resource
transformation and specifying a URI, your domain class will automatically be available as a REST resource in either XML or JSON formats. The transformation will automatically register the necessary RESTful URL mapping and create a controller called BookController
.
Resource
変換を追加してURIを指定することで、ドメインクラスは自動的にXML、JSONフォーマットをサポートするRESTリソースとして使用可能になります。
この変換は、必要なRESTful URL マッピングを自動的に登録し、BookController
と呼ばれるコントローラを作成します。BootStrap.groovy
:
BootStrap.groovy
に追加することで動作確認ができます。def init = { servletContext ->new Book(title:"The Stand").save() new Book(title:"The Shining").save() }
http://localhost:8080/myapp/books/1
のURLをたたいてみると、以下のようなレスポンスが表示されます:<?xml version="1.0" encoding="UTF-8"?> <book id="1"> <title>The Stand</title> </book>
http://localhost:8080/myapp/books/1.json
you will get a JSON response such as:
http://localhost:8080/myapp/books/1.json
に変更すると、以下のようなJSONレスポンスが得られます:
{"id":1,"title":"The Stand"}
formats
attribute of the Resource
transformation:
Resource
変換のformats
属性を設定します。
import grails.rest.*@Resource(uri='/books', formats=['json', 'xml']) class Book { … }
grails.mime.types
setting of Config.groovy
:
Config.groovy
のgrails.mime.types
設定の中で定義されます:grails.mime.types = [ … json: ['application/json', 'text/json'], … xml: ['text/xml', 'application/xml'] ]
curl
tool:
curl
コマンドを使用した例です:$ curl -i -H "Accept: application/json" localhost:8080/myapp/books/1 {"id":1,"title":"The Stand"}
POST
request:
POST
リクエスを発行することで新たなリソースを作成できます:$ curl -i -X POST -H "Content-Type: application/json" -d '{"title":"Along Came A Spider"}' localhost:8080/myapp/books HTTP/1.1 201 Created Server: Apache-Coyote/1.1 ...
PUT
request:
PUT
リクエストを使用します:$ curl -i -X PUT -H "Content-Type: application/json" -d '{"title":"Along Came A Spider"}' localhost:8080/myapp/books/1 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 ...
DELETE
request:
DELETE
リクエストでリソースが削除されます:$ curl -i -X DELETE localhost:8080/myapp/books/1 HTTP/1.1 204 No Content Server: Apache-Coyote/1.1 ...
Resource
transformation enables all of the HTTP method verbs on the resource. You can enable only read-only capabilities by setting the readOnly
attribute to true:
Resource
変換はリソースに対してHTTPメソッドに対応する動作のすべてを有効にします。
readOnly
属性をtrueに設定することで読み取り専用にできます:import grails.rest.*@Resource(uri='/books', readOnly=true) class Book { … }
8.1.2 RESTリソースへのマッピング
UrlMappings.groovy
file then simply removing the uri
attribute of the Resource
transformation and adding the following line to UrlMappings.groovy
will suffice:
UrlMappings.groovy
内にURLマッピングの宣言を保持したい場合は、単にResource
変換からuri
属性を削除して、UrlMappings.groovy
へ以下の行を追加するだけです:"/books"(resources:"book")
"/books"(resources:"book") { "/publisher"(controller:"publisher", method:"GET") }
/books/1/publisher
.
/books/1/publisher
というURIで公開されます。8.1.3 RESTリソースへのリンク
link
tag offers an easy way to link to any domain class resource:
link
タグは、任意のドメインクラスリソースへリンクする簡単な方法を提供します:<g:link resource="${book}">My Link</g:link>
8.1.4 RESTリソースのバージョニング
URIを使ったバージョンニング
"/books/v1"(resources:"book", namespace:'v1') "/books/v2"(resources:"book", namespace:'v2')
package myapp.v1class BookController { static namespace = 'v1' }
package myapp.v2
class BookController { static namespace = 'v2' }
Accept-Versionヘッダを使ったバージョンニング
Accept-Version
header from clients. For example you can define the following URL mappings:Accept-Version
ヘッダによる制御をサポートしています。
例えば以下のようにURLマッピングを定義できます:"/books"(version:'1.0', resources:"book", namespace:'v1') "/books"(version:'2.0', resources:"book", namespace:'v2')
Accept-Version
header:Accept-Version
ヘッダを使ってバージョンを渡すだけです:$ curl -i -H "Accept-Version: 1.0" -X GET http://localhost:8080/myapp/books
ハイパーメディア/MIMEタイプを使ったバージョニング
Config.groovy
you can declare a custom Mime Type for your resource that includes a version parameter (the 'v' parameter):
Config.groovy
内に、リソースに対してバージョンパラメータ('v'のパラメータ)を含んだカスタムMIMEタイプを宣言できます:grails.mime.types = [ all: '*/*', book: "application/vnd.books.org.book+json;v=1.0", bookv2: "application/vnd.books.org.book+json;v=2.0", … }
It is critical that place your new mime types after the 'all' Mime Type because if the Content Type of the request cannot be established then the first entry in the map is used for the response. If you have your new Mime Type at the top then Grails will always try and send back your new Mime Type if the requested Mime Type cannot be established.
'all'のMIMEタイプの後に、新たなMIMEタイプを宣言しているのには重要な意味があります。 なぜなら、リクエストのコンテンツタイプが不明な場合は、マップ内の最初のエントリがレスポンスのコンテンツタイプとして使われるためです。 もし、新たなMIMEタイプが先頭にあるとすると、リクエストのコンテンツタイプが不明な場合に、Grailsは新たなMIMEタイプを常に送り返すことになります。
grails-app/conf/spring/resourses.groovy
:grails-app/conf/spring/resourses.groovy
内でカスタムMIMEタイプを返すようにレンダリング設定(カスタムレンダリングのより詳しい情報は「レスポンスレンダリングのカスタマイズ」を参照してください)を上書きします:import grails.rest.renderer.json.* import org.codehaus.groovy.grails.web.mime.*beans = { bookRendererV1(JsonRenderer, myapp.v1.Book, new MimeType("application/vnd.books.org.book+json", [v:"1.0"])) bookRendererV2(JsonRenderer, myapp.v2.Book, new MimeType("application/vnd.books.org.book+json", [v:"2.0"])) }
Accept
header you can specify which version you need using the Mime Type:Accept
ヘッダでMIMEタイプを使いバージョンを指定できます。$ curl -i -H "Accept: application/vnd.books.org.book+json;v=1.0" -X GET http://localhost:8080/myapp/books
8.1.5 RESTコントローラの実装
Resource
transformation is a quick way to get started, but typically you'll want to customize the controller logic, the rendering of the response or extend the API to include additional actions.Resource
変換はREST APIを構築する手っ取り早い方法です。
しかし大抵の場合、レスポンスのレンダリングを変更したり、APIを拡張するなど、コントローラのロジックをカスタマイズしたくなります。
8.1.5.1 RestfulControllerスーパークラスの拡張
grails.rest.RestfulController
super class. For example:grails.rest.RestfulController
をスーパークラスとして、リソースに対して新たなコントローラを作成する方法です。
例えば:class BookController extends RestfulController { static responseFormats = ['json', 'xml'] BookController() { super(Book) } }
HTTP Method | URI | Controller Action |
---|---|---|
GET | /books | index |
GET | /books/create | create |
POST | /books | save |
GET | /books/${id} | show |
GET | /books/${id}/edit | edit |
PUT | /books/${id} | update |
DELETE | /books/${id} | delete |
Note that thecreate
andedit
actions are only needed if the controller exposes an HTML interface.
create
とedit
アクションは、コントローラがHTMLインタフェースを公開する場合にのみ必要です。
"/authors"(resources:'author') { "/books"(resources:'book') }
class BookController extends RestfulController { static responseFormats = ['json', 'xml'] BookController() { super(Book) }@Override Book queryForResource(Serializable id) { Book.where { id == id && author.id = params.authorId }.find() }
}
RestfulController
and overrides the queryForResource
method to customize the query for the resource to take into account the parent resource.RestfulController
のサブクラスで親リソースに対応するため、queryForResource
メソッドをオーバーライドしてリソースのクエリをカスタマイズしています。
8.1.5.2 RESTコントローラの実装ステップバイステップ
RestfulController
super class, then you can implement each HTTP verb yourself manually. The first step is to create a controller:RestfulController
から提供される機能を使用しない場合は、それぞれHTTPメソッドに対応するアクションを自身で実装できます。
最初のステップはコントローラの作成です:$ grails create-controller book
import grails.transaction.* import static org.springframework.http.HttpStatus.* import static org.springframework.http.HttpMethod.*@Transactional(readOnly = true) class BookController { … }
HTTP Method | URI | Controller Action |
---|---|---|
GET | /books | index |
GET | /books/${id} | show |
GET | /books/create | create |
GET | /books/${id}/edit | edit |
POST | /books | save |
PUT | /books/${id} | update |
DELETE | /books/${id} | delete |
The 'create' and 'edit' actions are already required if you plan to implement an HTML interface for the REST resource. They are there in order to render appropriate HTML forms to create and edit a resource. If this is not a requirement they can be discarded.
'create'と'edit'アクションはRESTリソースに対して、HTMLインタフェースを実装する予定がある場合は必要です。 これらはリソースの追加、編集のHTMLフォームを表示するためにあります。 これが必要ない場合は無効にできます。
respond
method tries to produce the most appropriate response for the requested content type (JSON, XML, HTML etc.)respond
メソッドは、リクエストのContent Type(JSON、XML、HTMLなど)に対して、もっとも適切なレスポンスを生成しようとします。'index'アクションの実装
index
action, simply call the respond
method passing the list of objects to respond with:
index
アクションを実装するには、単にオブジェクトのリストと共にrespond
メソッドを呼びます:def index(Integer max) { params.max = Math.min(max ?: 10, 100) respond Book.list(params), model:[bookCount: Book.count()] }
model
argument of the respond
method to supply the total count. This is only required if you plan to support pagination via some user interface.respond
メソッドにmodel
引数を渡しています。
これは、ユーザインタフェースでページングをサポートする場合にのみ必要です。respond
method will, using Content Negotiation, attempt to reply with the most appropriate response given the content type requested by the client (via the ACCEPT header or file extension).respond
メソッドは、コンテントネゴシエーションを使って、クライントからリクエストされたコンテンツタイプから(ACCEPTヘッダまたはファイル拡張子から)、もっとも適切なレスポンスを返そうとします。model
を生成します:def index(Integer max) { params.max = Math.min(max ?: 10, 100) [bookList: Book.list(params), bookCount: Book.count()] }
index.gsp
file you can render an appropriate view for the given model. If the content type is something other than HTML then the respond
method will attempt to lookup an appropriate grails.rest.render.Renderer
instance that is capable of rendering the passed object. This is done by inspecting the grails.rest.render.RendererRegistry
.index.gsp
ファイルを提供することで、与えられたmodel
に対するビューが表示できます。
もし、コンテンツタイプがHTMLではない場合、respond
メソッドは渡されたオブジェクトをレンダリングできる適切なgrails.rest.render.Renderer
のインスタンスを探します。
これはgrails.rest.render.RendererRegistry
から検索されます。'show'アクションの実装
show
action, which is used to display and individual resource by id, can be implemented in one line of Groovy code (excluding the method signature):show
アクションはidによって個々のリソースを表示するためのものです。
これはGroovyコード1行で実装できます(メソッドのシグネチャを除く):def show(Book book) { respond book }
id
parameter of the request. If the domain instance doesn't exist, then null
will be passed into the action. The respond
method will return a 404 error if null is passed otherwise once again it will attempt to render an appropriate response. If the format is HTML then an appropriate model will produced. The following action is functionally equivalent to the above action:
id
パラメータからドメインインスタンスを検索しようとします。
もし、ドメインインスタンスが存在しない場合は、アクションへnull
が渡されます。
respond
メソッドはnullが渡された場合は404エラーを返します。
nullではない場合は、前と同じように適切なレスポンスを表示しようとします。
もし、フォーマットがHTMLの場合は適切なmodel
を生成します。
以下のアクションは、上記のアクションと機能的に同じです:def show(Book book) { if(book == null) { render status:404 } else { return [book: book] } }
'save'アクションの実装
save
action creates new resource representations. To start off, simply define an action that accepts a resource as the first argument and mark it as Transactional
with the grails.transaction.Transactional
transform:
save
アクションは新たなリソースを保存します。
save
アクションを簡単に実装するには、最初の引数にリソースをとるアクションを定義し、そのアクションにgrails.transaction.Transactional
変換を使ってTransactional
としてマークします:@Transactional def save(Book book) { … }
errors
を応答します:if(book.hasErrors()) { respond book.errors, view:'create' } else { … }
book.save flush:true withFormat { html { flash.message = message(code: 'default.created.message', args: [message(code: 'book.label', default: 'Book'), book.id]) redirect book } '*' { render status: CREATED } }
'update'アクションの実装
update
action updates an existing resource representations and is largely similar to the save
action. First define the method signature:
update
アクションは既存のリソースを更新します。
そして、update
アクションはsave
アクションとほとんど同じです。
はじめにメソッドのシグネチャを定義します:@Transactional def update(Book book) { … }
if(book == null) { render status: NOT_FOUND } else { … }
errors
を応答します:if(book.hasErrors()) { respond book.errors, view:'edit' } else { … }
book.save flush:true withFormat { html { flash.message = message(code: 'default.updated.message', args: [message(code: 'book.label', default: 'Book'), book.id]) redirect book } '*' { render status: OK } }
'delete'アクションの実装
delete
action deletes an existing resource. The implementation is largely similar to the update
action, expect the delete()
method is called instead:delete
アクションは既存のリソースを削除します。
実装は、update
アクションとほとんど同じでdelete()
メソッドを代わりに呼びます:book.delete flush:true withFormat { html { flash.message = message(code: 'default.deleted.message', args: [message(code: 'Book.label', default: 'Book'), book.id]) redirect action:"index", method:"GET" } '*'{ render status: NO_CONTENT } }
index
action, whilst for other content types a response code 204 (NO_CONTENT) is returned.index
アクションへリダイレクトされます。
他のコンテンツタイプに対しては、レスポンスコード204(NO_CONTENT)が返されます。
8.1.5.3 スカッフォルドを使用してRESTコントローラを生成
$ grails generate-controller [Domain Class Name]
8.1.6 レスポンスレンダリングのカスタマイズ
8.1.6.1 デフォルトレンダラーのカスタマイズ
grails.rest.render.xml
and grails.rest.render.json
packages respectively. These use the Grails converters (grails.converters.XML
and grails.converters.JSON
) by default for response rendering.
grails.rest.render.xml
、grails.rest.render.json
パッケージ内にあります。
これらはレスポンスのレンダリングにGrailsのコンバータ(grails.converters.XML
とgrails.converters.JSON
)を使います。レンダリング時のプロパティのインクルードとエクスクルード
grails.rest.render.Renderer
instances. There are some default configured renderers and the ability to register or override renderers for a given domain class or even for a collection of domain classes. To include a particular property from rendering you need to register a custom renderer by defining a bean in grails-app/conf/spring/resources.groovy
:grails.rest.render.Renderer
インスタンスをレジストリで管理しています。
デフォルトで設定されているレンダラーがいくつかありますが、与えられたドメインクラス、またはドメインクラスのコレクションに対し、レンダラーの登録や上書きが可能です。
レンダリングで特定のプロパティをインクルードするには、grails-app/conf/spring/resources.groovy
内のビーン定義によって、カスタムレンダラーを登録する必要があります:import grails.rest.render.xml.*beans = { bookRenderer(XmlRenderer, Book) { includes = ['title'] } }
The bean name is not important (Grails will scan the application context for all registered renderer beans), but for organizational and readability purposes it is recommended you name it something meaningful.
ビーンの名前は重要ではありません(Grailsは登録されたすべてのレンダラーのビーンを見つけるために、アプリケーションコンテキストをスキャンします)。 しかし、構造と可読性の理由から、分かりやすい名前を付けておくことをお勧めします。
excludes
property of the XmlRenderer
class can be used:
XmlRenderer
クラスのexclude
プロパティを使います:import grails.rest.render.xml.*beans = { bookRenderer(XmlRenderer, Book) { excludes = ['isbn'] } }
コンバーターのカスタマイズ
grails.converters
package under the covers. In other words, under the covers they essentially do the following:
grails.converters
パッケージ配下のクラスを使っています。
これは、パッケージ配下のクラスを使って以下のようにした場合と本質的には同じです:import grails.converters.*… render book as XML
// or render book as JSON
8.1.6.2 カスタムオブジェクトマーシャラの登録
ObjectMarshaller
. You can register custom ObjectMarshaller
instances to completely customize response rendering. For example, you can define the following in BootStrap.init
:
ObjectMarshaller
を登録できます。
そして、レスポンスのレンダリングをカスタマイズするためにカスタムObjectMarshaller
インタンスを登録できます。
例えば、BootStrap.init
の中で以下のように定義できます:XML.registerObjectMarshaller Book, { Book book, XML xml -> xml.attribute 'id', book.id xml.build { title(book.title) } }
JSON.registerObjectMarshaller(DateTime) { return it?.toString("yyyy-MM-dd'T'HH:mm:ss'Z'") }
JSON.registerObjectMarshaller(Book) {
def map= [:]
map['titl'] = it.title
map['auth'] = it.author
return map
}
Spring経由でカスタムマーシャラを登録する
class CustomMarshallerRegistrar {@javax.annotation.PostConstruct void registerMarshallers() { JSON.registerObjectMarshaller(DateTime) { return it?.toString("yyyy-MM-dd'T'HH:mm:ss'Z'") } } }
grails-app/conf/spring/resources.groovy
:grails-app/conf/spring/resources.groovy
内でSpringビーンとして定義します:beans = { myCustomMarshallerRegistrar(CustomMarshallerRegistrar) }
PostConstruct
annotation will get triggered on startup of your application.PostConstruct
アノテーションはアプリケーション起動時に処理を起動するトリガーになります。
8.1.6.3 オブジェクト・マーシャラの名前付き定義
XML.createNamedConfig('publicApi') { it.registerObjectMarshaller(Book) { Book book, XML xml -> // do public API } } XML.createNamedConfig('adminApi') { it.registerObjectMarshaller(Book) { Book book, XML xml -> // do admin API } }
render
or respond
methods you can wrap the call in a named configuration if necessary to customize rendering per request:render
またはrespond
メソッドのどちらかを使い、名前付き設定でそのメソッド呼び出しをラップできます。XML.use( isAdmin ? 'adminApi' : 'publicApi') { render book as XML }
XML.use( isAdmin ? 'adminApi' : 'publicApi') { respond book }
8.1.6.4 ObjectMarshallerインターフェイスへの実装
class Book {
String title
}
render book as XML
<book id="1"> <title>The Stand</title> </book>
class BookMarshaller implements ObjectMarshaller<XML> {public boolean supports(Object object) { return object instanceof Book }
public void marshalObject(Object object, XML converter) { Book book = (Book)object converter.chars book.title } }
XML.registerObjectMarshaller(new BookMarshaller())
ObjectMarshaller
in place, the output is now:ObjectMarshaller
を登録すると、出力は次のようになります:<book>The Stand</book>
ルート要素の名前をカスタマイズする
class BookMarshaller implements ObjectMarshaller<XML>,NameAwareMarshaller {...
String getElementName(Object o) { return 'custom-book' }
}
<custom-book>The Stand</custom-book>
コンバータAPIまたはビルダーを使ってマークアップを出力する
public void marshalObject(Object object, XML converter) { Book book = (Book)objectconverter.attribute 'id', book.id.toString() converter.attribute 'date-released', book.dateReleased.toString()
converter.startNode 'title' converter.chars book.title converter.end()
}
<book id="1" date-released="..."> <title>The Stand</title> </book>
CompileStatic
):public void marshalObject(Object object, XML converter) { Book b = (Book)objectconverter.build { book(id: b.id) { title b.title } } }
再帰的にオブジェクトをコンバートするためにconvertAnotherメソッドを使う
convertAnother
method to convert associations and other objects:convertAnother
メソッドを使います:public void marshalObject(Object object, XML converter) { Book book = (Book)objectconverter.startNode 'title' converter.chars book.title converter.end()
if (book.authors) { converter.startNode 'authors' for(author in book.authors) { converter.convertAnother author } converter.end() } }
8.1.6.5 カスタムレンダラーの実装
Renderer
instance. For example below is a simple implementation that customizes the rendering of the Book
class:Renderer
インスタンスを実装できます。
例えば、以下はBook
クラスのレンダリングをカスタマイズする簡単な実装例です:package myapp import grails.rest.render.* import org.codehaus.groovy.grails.web.mime.MimeTypeclass BookXmlRenderer extends AbstractRenderer<Book> { BookXmlRenderer() { super(Book, [MimeType.XML,MimeType.TEXT_XML] as MimeType[]) }
void render(Book object, RenderContext context) { context.contentType = MimeType.XML.name
def xml = new groovy.xml.MarkupBuilder(context.writer) xml.book(id: object.id, title:object.title) } }
AbstractRenderer
super class has a constructor that takes the class that it renders and the MimeType
(s) that are accepted (via the ACCEPT header or file extension) for the renderer.AbstractRenderer
は、表示するクラスと、レンダラーが受け入れる(ACCEPT
ヘッダまたはファイル拡張子から取得した)MimeType
を(複数)取るコンストラクタを持っています。grails-app/conf/spring/resources.groovy
:grails-app/conf/spring/resources.groovy
へビーンを単に追加します:beans = { bookRenderer(myapp.BookXmlRenderer) }
Book
instances will be rendered in the following format:Book
インスタンスは以下のフォーマットで表示されます:<book id="1" title="The Stand"/>
Note that if you change the rendering to a completely different format like the above, then you also need to change the binding if you plan to support POST and PUT requests. Grails will not automatically know how to bind data from a custom XML format to a domain class otherwise. See the section on "Customizing Binding of Resources" for further information.
もし、POST・PUTリクエストをサポートする予定があり、上記のように完全に異なるフォーマットへレンダリングを変えたい場合は、バインディングもあわせて変更する必要があります。 Grailsは、カスタムXMLフォーマットから他のドメインクラスへ、どうのようにデータをバインドるするかを自動的に知ることはできません。 さらなる情報は「リソースバインディングのカスタマイズ」を参照してください。
コンテナレンダラー
grails.rest.render.ContainerRenderer
is a renderer that renders responses for containers of objects (lists, maps, collections etc.). The interface is largely the same as the Renderer
interface except for the addition of the getComponentType()
method, which should return the "contained" type. For example:grails.rest.render.ContainerRenderer
は、オブジェクトのコンテナ(リスト、マップ、コレクションなど)に対してレスポンスを表示するレンダラーです。
このインタフェースは、型パラメータが付与されたコンテナの型を返すgetComponentType()
メソッドが加えられている以外はRenderer
インタフェースとほとんど同じです。
例えば:class BookListRenderer implements ContainerRenderer<List, Book> { Class<List> getTargetType() { List } Class<Book> getComponentType() { Book } MimeType[] getMimeTypes() { [ MimeType.XML] as MimeType[] } void render(List object, RenderContext context) { .... } }
8.1.6.6 GSPを使用したカスタムレンダリング
show
action mentioned previously:def show(Book book) { respond book }
show.xml.gsp
file to customize the rendering of the XML:show.xml.gsp
ファイルを用意します:<%@page contentType="application/xml"%> <book id="${book.id}" title="${book.title}"/>
8.1.7 アプリケーション状態エンジンとしてのハイパーメディア
8.1.7.1 HALサポート
{ "_links": { "self": { "href": "/orders" }, "next": { "href": "/orders?page=2" }, "find": { "href": "/orders{?id}", "templated": true }, "admin": [{ "href": "/admins/2", "title": "Fred" }, { "href": "/admins/5", "title": "Kate" }] }, "currentlyProcessing": 14, "shippedToday": 20, "_embedded": { "order": [{ "_links": { "self": { "href": "/orders/123" }, "basket": { "href": "/baskets/98712" }, "customer": { "href": "/customers/7809" } }, "total": 30.00, "currency": "USD", "status": "shipped" }, { "_links": { "self": { "href": "/orders/124" }, "basket": { "href": "/baskets/97213" }, "customer": { "href": "/customers/12369" } }, "total": 20.00, "currency": "USD", "status": "processing" }] } }
HALを使ったリソースの公開
grails-app/conf/spring/resources.groovy
with an instance of grails.rest.render.hal.HalJsonRenderer
(or HalXmlRenderer
for the XML variation):grails.rest.render.hal.HalJsonRenderer
(XMLの場合はHalXmlRenderer
)のインスタンスを使い、grails-app/conf/spring/resources.groovy
の中でレンダラーを単に上書きします:import grails.rest.render.hal.* beans = { halBookRenderer(HalJsonRenderer, rest.test.Book) }
$ curl -i -H "Accept: application/hal+json" http://localhost:8080/myapp/books/1HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: application/hal+json;charset=ISO-8859-1
{ "_links": { "self": { "href": "http://localhost:8080/myapp/books/1", "hreflang": "en", "type": "application/hal+json" } }, "title": ""The Stand"" }
import grails.rest.render.hal.* beans = { halBookRenderer(HalXmlRenderer, rest.test.Book) }
カスタムMIME(メディア)タイプの使用
grails-app/conf/Config.groovy
:grails-app/conf/Config.groovy
の中でMIMEタイプを宣言する必要があります:grails.mime.types = [ all: "*/*", book: "application/vnd.books.org.book+json", bookList: "application/vnd.books.org.booklist+json", … ]
It is critical that place your new mime types after the 'all' Mime Type because if the Content Type of the request cannot be established then the first entry in the map is used for the response. If you have your new Mime Type at the top then Grails will always try and send back your new Mime Type if the requested Mime Type cannot be established.
'all'のMIMEタイプの後に、新たなMIMEタイプを宣言しているのには重要な意味があります。 なぜなら、リクエストのコンテンツタイプが不明な場合は、マップ内の最初のエントリがレスポンスのコンテンツタイプとして使われるためです。 もし、新たなMIMEタイプが先頭にあるとすると、リクエストのコンテンツタイプが不明な場合に、Grailsは新たなMIMEタイプを常に送り返すことになります。
import grails.rest.render.hal.* import org.codehaus.groovy.grails.web.mime.*beans = { halBookRenderer(HalJsonRenderer, rest.test.Book, new MimeType("application/vnd.books.org.book+json", [v:"1.0"])) halBookListRenderer(HalJsonCollectionRenderer, rest.test.Book, new MimeType("application/vnd.books.org.booklist+json", [v:"1.0"])) }
application/vnd.books.org.book+json
. The second bean defines the Mime Type used to render a collection of books (in this case application/vnd.books.org.booklist+json
).application/vnd.books.org.book+json
のMIMEタイプを返すHALのレンダラーを定義しています。
2つ目のビーンはbookのコレクションを表示するために使われるMIMEタイプを定義しています(この場合はapplication/vnd.books.org.booklist+json
)。$ curl -i -H "Accept: application/vnd.books.org.book+json" http://localhost:8080/myapp/books/1HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: application/vnd.books.org.book+json;charset=ISO-8859-1
{ "_links": { "self": { "href": "http://localhost:8080/myapp/books/1", "hreflang": "en", "type": "application/vnd.books.org.book+json" } }, "title": ""The Stand"" }
リンクレンダリングのカスタマイズ
HalJsonRenderer
will automatically create links for you for associations and to the resource itself (using the "self" relationship).HalJsonRenderer
は、関連と("self"関連を使って)自身のリソースへのリンクを自動的に作成します。link
method that is added to all domain classes annotated with grails.rest.Resource
or any class annotated with grails.rest.Linkable
. For example, the show
action can be modified as follows to provide a new link in the resulting output:
grails.rest.Resource
が付与されたドメインクラス、またはgrails.rest.Linkable
が付与されたクラスに追加されたlink
メソッドを使って、カスタマイズすることもできます。
例えば、show
アクションで結果を出力する際に新たなリンクを追加するには、以下のように変更します:def show(Book book) {
book.link rel:'publisher', href: g.link(resource:"publisher", params:[bookId: book.id])
respond book
}
{ "_links": { "self": { "href": "http://localhost:8080/myapp/books/1", "hreflang": "en", "type": "application/vnd.books.org.book+json" } "publisher": { "href": "http://localhost:8080/myapp/books/1/publisher", "hreflang": "en" } }, "title": ""The Stand"" }
link
method can be passed named arguments that match the properties of the grails.rest.Link
class.link
メソッドはgrails.rest.Link
クラスのプロパティに一致する名前付き引数を渡せます。
8.1.7.2 Atomサポート
<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"><title>Example Feed</title> <link href="http://example.org/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>John Doe</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://example.org/2003/12/13/atom03"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry>
</feed>
import grails.rest.render.atom.* beans = { halBookRenderer(AtomRenderer, rest.test.Book) halBookListRenderer(AtomCollectionRenderer, rest.test.Book) }
8.1.7.3 Vnd.Errorサポート
$ curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d "" http://localhost:8080/myapp/booksHTTP/1.1 422 Unprocessable Entity Server: Apache-Coyote/1.1 Content-Type: application/json;charset=ISO-8859-1
{"errors":[{"object":"rest.test.Book","field":"title","rejected-value":null,"message":"Property [title] of class [class rest.test.Book] cannot be null"}]}
grails.rest.render.errors.VndErrorJsonRenderer
bean in grails-app/conf/spring/resources.groovy
:grails-app/conf/spring/resources.groovy
の中にgrails.rest.render.errors.VndErrorJsonRenderer
ビーンを単に登録します:
beans = { vndJsonErrorRenderer(grails.rest.render.errors.VndErrorJsonRenderer) // for Vnd.Error XML format vndXmlErrorRenderer(grails.rest.render.errors.VndErrorXmlRenderer) }
$ curl -i -H "Accept: application/vnd.error+json,application/json" -H "Content-Type: application/json" -X POST -d "" http://localhost:8080/myapp/books HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: application/vnd.error+json;charset=ISO-8859-1[ { "logref": ""book.nullable"", "message": "Property [title] of class [class rest.test.Book] cannot be null", "_links": { "resource": { "href": "http://localhost:8080/rest-test/books" } } } ]
8.1.8 リソースバインディングのカスタマイズ
request
property in a controller the properties
of a domain class. Given the following XML as the body of the request, the createBook
action will create a new Book
and assign "The Stand" to the title
property and "Stephen King" to the authorName
property.request
プロパティをドメインクラスのプロパティへバインドすることです。
リクエストのボディとして以下のようなXMLを与えた場合、createBook
アクションは新しいBook
を作成し、"The Stand"をtitle
プロパティへ、"Stephen King"をauthorName
プロパティへ代入します。<?xml version="1.0" encoding="UTF-8"?> <book> <title>The Stand</title> <authorName>Stephen King</authorName> </book>
class BookController {def createBook() { def book = new Book() book.properties = request
// … } }
id
attribute, the id
value will be used to retrieve the corresponding persistent instance from the database and then the rest of the document will be bound to the instance. If no corresponding record is found in the database, the command object reference will be null.id
属性を含む場合は、そのid
値はデータベースから対応する永続化インスタンスを検索するために使われます。
そして、ドキュメントの残りはインスタンスへバインドされます。
もし、一致するレコードがデータベース内に見つからない場合は、コマンドオブジェクトの参照はnullになります。<?xml version="1.0" encoding="UTF-8"?> <book> <title>The Stand</title> <authorName>Stephen King</authorName> </book>
class BookController { def createBook(BookCommand book) {// … } }
class BookCommand { String title String authorName }
id
attribute, the id
value will be used to retrieve the corresponding persistent instance from the database and then the rest of the document will be bound to the instance. If no corresponding record is found in the database, the command object reference will be null.id
属性を含んでいる場合は、そのid
値はデータベースから対応する永続化インスタンスを検索するために使われます。
そして、ドキュメントの残りはインスタンスへバインドされます。
もし、一致するレコードがデータベース内に見つからない場合は、コマンドオブジェクトの参照はnullになります。<?xml version="1.0" encoding="UTF-8"?> <book id="42"> <title>Walden</title> <authorName>Henry David Thoreau</authorName> </book>
class BookController { def updateBook(Book book) { // The book will have been retrieved from the database and updated // by doing something like this: // // book == Book.get('42') // if(book != null) { // book.properties = request // } // // the code above represents what the framework will // have done. There is no need to write that code.// ...
} }
DataBindingSourceCreator
will be selected based on the contentType
of the request. Several implementations
are provided to handle common content types. The default implementations will be fine for most use cases. The following table
lists the content types which are supported by the core framework and which DataBindingSourceCreator
implementations are used for each.DataBindingSourceCreator
の具体的な実装はリクエストのcontentType
を元に選択されます。
主要なコンテンツタイプをハンドリングするためにいくつかの実装が提供されています。
大抵の場合にこのデフォルト実装で十分なはずです。
以下のテーブルのコンテンツタイプ一覧がコアフレームワークによってサポートされており、それぞれ対応するDataBindingSourceCreator
の実装が使われます。Content Type(s) | Bean Name | DataBindingSourceCreator Impl. |
---|---|---|
application/xml, text/xml | xmlDataBindingSourceCreator | org.codehaus.groovy.grails.web.binding.bindingsource.XmlDataBindingSourceCreator |
application/json, text/json | jsonDataBindingSourceCreator | org.codehaus.groovy.grails.web.binding.bindingsource.JsonDataBindingSourceCreator |
application/hal+json | halJsonDataBindingSourceCreator | org.codehaus.groovy.grails.web.binding.bindingsource.HalJsonDataBindingSourceCreator |
application/hal+xml | halXmlDataBindingSourceCreator | org.codehaus.groovy.grails.web.binding.bindingsource.HalXmlDataBindingSourceCreator |
コンテンツタイプ | ビーン名 | DataBindingSourceCreator実装 |
---|---|---|
application/xml, text/xml | xmlDataBindingSourceCreator | org.codehaus.groovy.grails.web.binding.bindingsource.XmlDataBindingSourceCreator |
application/json, text/json | jsonDataBindingSourceCreator | org.codehaus.groovy.grails.web.binding.bindingsource.JsonDataBindingSourceCreator |
application/hal+json | halJsonDataBindingSourceCreator | org.codehaus.groovy.grails.web.binding.bindingsource.HalJsonDataBindingSourceCreator |
application/hal+xml | halXmlDataBindingSourceCreator | org.codehaus.groovy.grails.web.binding.bindingsource.HalXmlDataBindingSourceCreator |
DataBindingSourceCreator
for any of those content types, write a class which implements
DataBindingSourceCreator
and register an instance of that class in the Spring application context. If you
are replacing one of the existing helpers, use the corresponding bean name from above. If you are providing a
helper for a content type other than those accounted for by the core framework, the bean name may be anything that
you like but you should take care not to conflict with one of the bean names above.DataBindingSourceCreator
を提供するには、DataBindingSourceCreator
の実装クラスを書き、Springのアプリケーションコンテキスト内にそのクラスのインスタンスを登録します。
既存のヘルパーを置き換える場合は、上記のビーン名に対応する名前を使います。
もし、これらコアフレームによって提供される以外のコンテンツタイプのヘルパーを提供する場合、ビーンの名前は何でも好きに設定可能ですが、上記のビーン名と競合しないように注意してください。DataBindingSourceCreator
interface defines just 2 methods:DataBindingSourceCreator
インタフェースは2つのメソッドを定義しています:package org.grails.databinding.bindingsourceimport org.codehaus.groovy.grails.web.mime.MimeType import org.grails.databinding.DataBindingSource
/** * A factory for DataBindingSource instances * * @since 2.3 * @see DataBindingSourceRegistry * @see DataBindingSource * */ interface DataBindingSourceCreator {
/** *
return All of the {
link MimeType} supported by this helper */ MimeType[] getMimeTypes()/** * Creates a DataBindingSource suitable for binding bindingSource to bindingTarget * * @param mimeType a mime type * @param bindingTarget the target of the data binding * @param bindingSource the value being bound * @return a DataBindingSource */ DataBindingSource createDataBindingSource(MimeType mimeType, Object bindingTarget, Object bindingSource) }
DataBindingSourceCreator
classes. Classes which
extend AbstractRequestbodyDatabindingSourceCreator
need to implement a method named createBindingSource
which accepts an InputStream
as an argument and returns a DataBindingSource
as well as implementing the getMimeTypes
method described in the DataBindingSourceCreator
interface above. The InputStream
argument to createBindingSource
provides access to the body of the request.DataBindingSourceCreator
クラスを書けるよう設計された抽象クラスです。
AbstractRequestbodyDatabindingSourceCreator
を継承したクラスは、引数としてInputStream
を受け取りDataBindingSource
を返す、createBindingSource
という名前のメソッドを実装する必要があります。
また、上記のDataBindingSourceCreator
インタフェース内で宣言されたgetMimeTypes
メソッドの実装が必要です。
createBindingSource
へのInputStream
の引数は、リクエストボディへのアクセスを提供します。
// src/groovy/com/demo/myapp/databinding/MyCustomDataBindingSourceCreator.groovy package com.demo.myapp.databindingimport org.codehaus.groovy.grails.web.mime.MimeType import org.grails.databinding.DataBindingSource import org.grails.databinding.SimpleMapDataBindingSource import org.grails.databinding.bindingsource.AbstractRequestBodyDataBindingSourceCreator
/** * A custom DataBindingSourceCreator capable of parsing key value pairs out of * a request body containing a comma separated list of key:value pairs like: * * name:Herman,age:99,town:STL * */ class MyCustomDataBindingSourceCreator extends AbstractRequestBodyDataBindingSourceCreator {
@Override public MimeType[] getMimeTypes() { [new MimeType('text/custom+demo+csv')] as MimeType[] }
@Override protected DataBindingSource createBindingSource(InputStream inputStream) { def map = [:]
def reader = new InputStreamReader(inputStream)
// this is an obviously naive parser and is intended // for demonstration purposes only.
reader.eachLine { line -> def keyValuePairs = line.split(',') keyValuePairs.each { keyValuePair -> if(keyValuePair?.trim()) { def keyValuePieces = keyValuePair.split(':') def key = keyValuePieces[0].trim() def value = keyValuePieces[1].trim() map[key] = value } } }
// create and return a DataBindingSource which contains the parsed data new SimpleMapDataBindingSource(map) } }
MyCustomDataSourceCreator
needs to be registered in the spring application context.MyCustomDataSourceCreator
のインスタンスはSpringのアプリケーションコンテキスト内に登録が必要です。// grails-app/conf/spring/resources.groovy beans = {myCustomCreator com.demo.myapp.databinding.MyCustomDataBindingSourceCreator
// … }
myCustomCreator
bean any time a DataBindingSourceCreator
is needed
to deal with a request which has a contentType
of "text/custom+demo+csv".contentType
を持ったリクエストを処理するDataBindingSourceCreator
が必要な場合に、myCustomCreator
ビーンを使います。
8.2 SOAP
Grails does not feature SOAP support out-of-the-box, but there are several plugins that can help for both producing SOAP servers and calling SOAP web services.SOAP Clients
To call SOAP web services there are generally 2 approaches taken, one is to use a tool to generate client stubs, the other is to manually construct the SOAP calls. The former can be easier to use, but the latter provides more flexibility / control.
The CXF client plugin uses the CXF framework, which includes a wsdl2java
tool for generating a client. There is nothing Groovy/Grails specific here in the generated code as it simply provides a Java API which you can invoke to call SOAP web services.
See the documentation on the CXF client plugin for further information.
Alternatively, if you prefer more control over your SOAP calls the WS-Lite library is an excellent choice and features a Grails plugin. You have more control over the SOAP requests sent, and since Groovy has fantastic support for building and parsing XML it can be very productive approach.
Below is an example of a SOAP call with wslite:
withSoap(serviceURL: 'http://www.holidaywebservice.com/Holidays/US/Dates/USHolidayDates.asmx') { def response = send { body { GetMothersDay(xmlns: 'http://www.27seconds.com/Holidays/US/Dates/') { year(2011) } } } println response.GetMothersDayResponse.GetMothersDayResult.text() }
It is not recommended that you use the GroovyWS library, it pulls in many dependencies which increases the likelihood of conflicts. The WSlite library provides a far simpler and easier to use solution.
SOAP Servers
Again, Grails does not have direct support for exposing SOAP web services, however if you wish to expose a SOAP service from your application then the CXF plugin (not to be confused with the cxf-client plugin), provides an easy way to do so.
Typically it involves taking a Grails service and adding 'expose'-style configuration, such as the below:
static expose = EndpointType.JAX_WS_WSDL //your path (preferred) or url to wsdl static wsdl = 'org/grails/cxf/test/soap/CustomerService.wsdl'
Please refer to the documentation of the plugin for more information.
8.3 RSSとAtom
def feed() { render(feedType: "rss", feedVersion: "2.0") { title = "My test feed" link = "http://your.test.server/yourController/feed"for (article in Article.list()) { entry(article.title) { link = "http://your.test.server/article/${article.id}" article.content // return the content } } } }
9 非同期プログラミング
9.1 Promises
java.util.concurrent.Future
instances, but include a more user friendly exception handling model, useful features like chaining and the ability to attach listeners.
java.util.concurrent.Future
によく似ていますが、より使いやすい例外ハンドリングモデルや、非同期処理の連鎖、リスナーの追加といったさまざまな便利な機能を備えています。Promise Basics
Promiseの基本
grails.async.Promises
class provides the entry point to the Promise API:
grails.async.Promises
クラスを提供しています。import static grails.async.Promises.*
task
method, which returns an instance of the grails.async.Promise
interface:
task
メソッドを使用します。これはgrails.async.Promise
インタフェースのインタンスを返します。def p1 = task { 2 * 2 } def p2 = task { 4 * 4 } def p3 = task { 8 * 8 } assert [4,16,64] == waitAll(p1, p2, p3)
waitAll
method waits synchronously, blocking the current thread, for all of the concurrent tasks to complete and returns the results.
waitAll
メソッドは現在のスレッドをブロックした状態で処理を待ち合わせ、すべての並行タスクが完了した時点で結果を返します。onComplete
method:
onComplete
メソッドを使用します。onComplete([p1,p2,p3]) { List results -> assert [4,16,64] == results }
waitAll
method will throw an exception if an error occurs executing one of the promises. The originating exception will be thrown. The onComplete
method, however, will simply not execute the passed closure if an exception occurs. You can register an onError
listener if you wish to handle exceptions without blocking:
waitAll
メソッドはpromiseのいずれかでエラーが発生した場合に例外をスローします。これは発信元の例外がスローされます。onComplete
メソッドを使用した場合は、単にクロージャが実行されないだけです。もしブロッキングせずに例外を処理したい場合はonError
メソッドを使用してリスナーを登録できます。onError([p1,p2,p3]) { Throwable t ->
println "An error occured ${t.message}"
}
grails.async.Promise
interface provides a similar API on the promise itself. For example:
grails.async.Promise
インターフェース自身で同様のAPIを提供しています。例えば以下のように使用します。import static java.util.concurrent.TimeUnit.* import static grails.async.Promises.*Promise p = task { // Long running task } p.onError { Throwable err -> println "An error occured ${err.message}" } p.onComplete { result -> println "Promise returned $result" } // block until result is called def result = p.get() // block for the specified time def result = p.get(1,MINUTES)
Promise Chaining
Promiseのチェーン
then
method:
then
メソッドを使用してpromiseをチェーンすることで、チェーンの完了を待ち合わせることができます。final polish = { … } final transform = { … } final save = { … } final notify = { … }Promise promise = task { // long running task } promise.then polish then transform then save then { // notify end result }
Promise Lists and Maps
Promiseのリストとマップ
grails.async.PromiseList
and grails.async.PromiseMap
classes respectively.
grails.async.PromiseList
、grails.async.PromiseMap
のクラスとして実装されています。tasks
method of the Promises
class:
Promises
クラスのtasks
メソッドを使用することです。import static grails.async.Promises.*def promiseList = tasks { 2 * 2 }, { 4 * 4}, { 8 * 8 }
assert [4,16,64] == promiseList.get()
tasks
method, when passed a list of closures, returns a PromiseList
. You can also construct a PromiseList
manually:
tasks
メソッドはクロージャのリストを引数に取りPromiseList
を返します。または手動でPromiseList
を構築することもできます。import grails.async.*def list = new PromiseList() list << { 2 * 2 } list << { 4 * 4 } list << { 8 * 8 } list.onComplete { List results -> assert [4,16,64] == results }
The PromiseList
class does not implement the java.util.List interface, but instead returns a java.util.List from the get() method
PromiseList
クラスはjava.util.Listのインタフェースを実装していません。代わりにget()メソッドを使用することでjava.util.Listとして取得できます。
PromiseMap
instances is largely similar. Again you can either use the tasks
method:
PromiseMap
を扱う場合もほとんど同じです。tasks
メソッドを使用する場合は以下のようにします。
import static grails.async.Promises.*def promiseList = tasks one:{ 2 * 2 }, two:{ 4 * 4}, three:{ 8 * 8 }
assert [one:4,two:16,three:64] == promiseList.get()
PromiseMap
manually:
PromiseMap
を使用して構築する場合は以下のようにします。import grails.async.*def list = new PromiseMap() map['one'] = { 2 * 2 } map['two'] = { 4 * 4 } map['three'] = { 8 * 8 } map.onComplete { Map results -> assert [one:4,two:16,three:64] == results }
Promise Factories
Promiseファクトリ
Promises
class uses a grails.async.PromiseFactory
instance to create Promise
instances.
Promises
クラスはPromise
インスタンスを生成するためにgrails.async.PromiseFactory
インスタンスを使用しています。org.grails.async.factory.gpars.GparsPromiseFactory
, however it is possible to swap implementations by setting the Promises.promiseFactory
variable.
org.grails.async.factory.gpars.GparsPromiseFactory
が使用されていますが、Promises.promiseFactory
の値を変更することで実装を差し替えることができます。org.grails.async.factory.SynchronousPromiseFactory
instance that makes it easier to test promises:
org.grails.async.factory.SynchronousPromiseFactory
を提供しており、これを使用することで簡単にpromiseのテストが行えます。import org.grails.async.factory.* import grails.async.*Promises.promiseFactory = new SynchronousPromiseFactory()
PromiseFactory
mechanism is theoritically possible to plug in other concurrency libraries into the Grails framework.
PromiseFactory
の仕組みを使用することで、Grailsに他の並行ライブラリを組み込みということも論理的には可能です。DelegateAsync Transformation
DelegateAsync変換
DelegateAsync
transformation is designed to mitigate this problem by transforming any synchronous API into an asynchronous one.
DelegateAsync
変換は、同期APIを非同期APIに変換することで、この問題を軽減できるように設計しています。class BookService {
List<Book> findBooks(String title) {
// implementation
}
}
findBooks
method executes synchronously in the same thread as the caller. To make an asynchronous version of this API you can define another class as follows:
findBooks
メソッドは呼び出し元と同じスレッドで同期的に実行されます。ここで次のような別クラスを定義することで、このAPIの非同期バージョンを作成できます。import grails.async.*class AsyncBookService { @DelegateAsync BookService bookService }
DelegateAsync
transformation will automatically add a new method that looks like the following to the AsyncBookService
class:
DelegateAsync
変換は、自動的にAsyncBookService
クラスに次のようなメソッドを追加します。Promise<List<Book>> findBooks(String title) {
Promises.task {
bookService.findBooks(title)
}
}
DelegateAsync
変換は非同期に処理を行い、Promiseを返すメソッドを追加します。AsyncBookService
can then be injected into other controllers and services and used as follows:
AsyncBookService
は、他のコントローラやサービスに注入され、次のように使用できます。AsyncBookService asyncBookService def findBooks(String title) { asyncBookService.findBooks(title) .onComplete { List results -> println "Books = ${results}" } }
9.2 非同期GORM
Async Namespace
Asyncネームスペース
async
namespace.
async
ネームスペースを通じて提供されます。import static grails.async.Promises.*def p1 = Person.async.get(1L) def p2 = Person.async.get(2L) def p3 = Person.async.get(3L) def results = waitAll(p1, p2, p3)
async
namespace, all the regular GORM methods are available (even dynamic finders), but instead of executing synchronously, the query is run in the background and a Promise
instance is returned.
async
ネームスペースでは、通常使用可能なすべてのGORMメソッドが使用できます(ダイナミックファインダーのような)。ただし同期的に実行されるのではなく、バックグラウンドでクエリーが実行され、Promise
インスタンスを返します。import static grails.async.Promises.*Person.async.list().onComplete { List results -> println "Got people = ${results}" } def p = Person.async.getAll(1L, 2L, 3L) List results = p.get()
def p1 = Person.async.findByFirstName("Homer") def p2 = Person.async.findByFirstName("Bart") def p3 = Person.async.findByFirstName("Barney") results = waitAll(p1, p2, p3)
Async and the Session
非同期とセッション
def promise = Person.async.findByFirstName("Homer") def person = promise.get() person.firstName = "Bart" person.save()
def promise = Person.async.findByFirstName("Homer") def person = promise.get() person.merge() person.firstName = "Bart"
merge()
is called first because it may refresh the object from the cache or database, which would result in the change being lost. In general it is not recommended to read and write objects in different threads and you should avoid this technique unless absolutely necessary.
merge()
を呼びだしています。これはキャッシュまたはデータベースのデータが再読み込みされ、それまでに行った変更が失われてしまうためです。また一般的に異なるスレッド間でオブジェクトを読み書きすることは推奨されません。もし必要がない限り、この方法は絶対に避けるべきです。LazyInitializationException
errors if you do so. If you plan to access the associated objects of those returned from asynchronous queries you should use eager queries (which is recommended anyway to avoid N+1 problems).
LazyInitializationException
を引き起こすという問題があります。もし非同期クエリから取得したオブジェクトの関連にアクセスする場合は、eagerクエリとして実行してください(N+1問題を避けるために、強くお勧めします)。Multiple Asynchronous GORM calls
複数の非同期GORMの呼び出し
task
method that makes this possible. For example:
task
メソッドを使用することで、より複雑なGORMの非同期処理が可能になります。例えば以下のように使用します。def promise = Person.async.task { withTransaction { def person = findByFirstName("Homer") person.firstName = "Bart" person.save(flush:true) } }Person updatedPerson = promise.get()
task
method differs from the static Promises.task
method in that it deals with binding a new session to the asynchronous thread for you. If you do not use the GORM version and do asynchronous work with GORM then you need to do this manually. Example:
task
メソッドは静的なPromises.task
メソッドとは異なり、非同期処理のスレッドに対して自動的に新いセッションをバインドします。もしGORMのtask
メソッドを使用せず非同期にGORMの処理を行う場合は、これを手動で行う必要があります。import static grails.async.Promises.*def promise = task { Person.withNewSession { // your logic here } }
Async DetachedCriteria
非同期DetachedCriteria
DetachedCriteria
class also supports the async
namespace. For example you can do the following:
async
ネームスペースをサポートしています。例えば次のように使用できます。DetachedCriteria query = Person.where { lastName == "Simpson" }def promise = query.async.list()
9.3 非同期リクエストハンドリング
Promise
mechism discussed previously.
Promise
の仕組みを使い、簡単に非同期レスポンスが作成できるAPIを提供しています。grails.servlet.version = "3.0"
Async Models
非同期モデル
grails.async.PromiseMap
via the Promises.tasks
method:
Promises.tasks
メソッドを使用しgrails.async.PromiseMap
を返すことで非同期にモデルを生成できます。import static grails.async.Promises.* … def index() { tasks books: Book.async.list(), totalBooks: Book.async.count(), otherValue: { // do hard work } }
def index() { def otherValue = … [ books: Book.list() , totalBooks: Book.count(), otherValue: otherValue ] }
PromiseMap
to the model
attribute of the render
method:
render
メソッドのmodel
属性にPromiseMap
を設定します。import static grails.async.Promises.* … def index() { render view:"myView", model: tasks( one:{ 2 * 2 }, two:{ 3 * 3 } ) }
Async Response Rendering
非同期レスポンスのレンダリング
import static grails.async.Promises.* class StockController {def stock(String ticker) { task { ticker = ticker ?: 'GOOG' def url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s=${ticker}&f=nsl1op&e=.csv") Double price = url.text.split(',')[-1] as Double render "ticker: $ticker, price: $price" } } }
Promise
instance from the controller action.
Promise
インスタンスを返します。9.4 Servlet 3.0 Async
Servlet 3.0 Asynchronous Rendering
Servlet 3.0の非同期レンダリング
startAsync
method which returns an instance of the Servlet 3.0 AsyncContext
. Once you have a reference to the AsyncContext
you can use Grails' regular render method to render content:
AsyncContext
インスタンスを返す、startAsync
を使用します。このメソッドを使用してAsyncContext
への参照を取得したら、あとは通常のrenderメソッドを使用してコンテンツをレンダリングするだけです。def index() { def ctx = startAsync() ctx.start { new Book(title:"The Stand").save() render template:"books", model:[books:Book.list()] ctx.complete() } }
complete()
method to terminate the connection.
complete
メソッドを呼び出す必要があることに注意してください。Resuming an Async Request
非同期リクエストの再開
dispatch
method of the AsyncContext
class:
AsyncContext
クラスのdispatch
メソッドを使用します。def index() {
def ctx = startAsync()
ctx.start {
// do working
…
// render view
ctx.dispatch()
}
}
10 バリデーション
constraints
)によってバリデーションを定義するすてきな仕組みを持っています。10.1 制約を宣言
class User { String login String password String email Integer agestatic constraints = { … } }
class User { ...static constraints = { login size: 5..15, blank: false, unique: true password size: 5..15, blank: false email email: true, blank: false age min: 18 } }
login
property must be between 5 and 15 characters long, it cannot be blank and must be unique. We've also applied other constraints to the password
, email
and age
properties.login
プロパティに対して5~15文字の長さとし(size
)、空白(blank
)を許可せず、一意となる(unique
)よう制約を与えています。password
、email
、age
の各プロパティについても同様に制約を宣言しています。
By default, all domain class properties are not nullable (i.e. they have an implicit nullable: false
constraint).
デフォルトでは、すべてのドメインクラスのプロパティはnull値を許容しません(暗黙にnullable: false
制約を持っています)。
java.util.Date
.java.util.Date
のインスタンスのような値を必要とするかもしれないため、制約が評価されるのは一度だけであることに注意してください。class User { ...static constraints = { // this Date object is created when the constraints are evaluated, not // each time an instance of the User class is validated. birthDate max: new Date() } }
class User { ...static constraints = { // この Date 型オブジェクトは制約が評価されるときに作られます。 // User クラスのインスタンスがバリデーションされる度に作られるわけではありません。 birthDate max: new Date() } }
忠告 - 制約からドメインクラスのプロパティを参照するとき
MissingPropertyException
for your trouble. For example, you may tryMissingPropertyException
が発生します。たとえば、以下のようなコードを試してみると…class Response { Survey survey Answer answerstatic constraints = { survey blank: false answer blank: false, inList: survey.answers } }
inList
constraint references the instance property survey
? That won't work. Instead, use a custom validator:inList
制約においてインスタンスプロパティであるsurvey
を参照すると、これは動作しません。代わりに、カスタムvalidatorを使いましょう:class Response { … static constraints = { survey blank: false answer blank: false, validator: { val, obj -> val in obj.survey.answers } } }
obj
argument to the custom validator is the domain instance that is being validated, so we can access its survey
property and return a boolean to indicate whether the new value for the answer
property, val
, is valid.obj
は、バリデーションされるドメインクラスの インスタンス です。こうすることでsurvey
プロパティにアクセスし、answer
プロパティの新しい値としてval
がsurvey.answers
に含まれるかどうかを示す真偽値を得ることができます。
10.2 制約をバリデートする
バリデーションの基礎
def user = new User(params)if (user.validate()) { // do something with user } else { user.errors.allErrors.each { println it } }
errors
property on domain classes is an instance of the Spring Errors interface. The Errors
interface provides methods to navigate the validation errors and also retrieve the original values.errors
プロパティは、SpringのErrorsインターフェイスのインスタンスです。Errors
インターフェイスは、バリデーションエラーの参照や元の値の取得などのメソッドを提供します。バリデーションのフェーズ
def user = new User(params)
errors
property due to type conversion (such as converting Strings to Dates). You can check these and obtain the original input value using the Errors
API:errors
プロパティが存在する場合があります(文字列を日付に変換しようとするなど)。Errors
APIを使用することで、エラーの有無や元の入力値を取得することができます:if (user.hasErrors()) { if (user.errors.hasFieldErrors("login")) { println user.errors.getFieldError("login").rejectedValue } }
validate
before executing, allowing you to write code like:validate
を呼び出すので、次のようなコードが書けます:if (user.save()) { return user } else { user.errors.allErrors.each { println it } }
10.3 制約をクラス間で共有する
Global Constraints
グローバル制約
grails-app/conf/Config.groovy
:
grails-app/conf/Config.groovy
内でも制約を定義できます。grails.gorm.default.constraints = { '*'(nullable: true, size: 1..20) myShared(nullable: false, blank: false) }
class User { ...static constraints = { login shared: "myShared" } }
shared
argument, whose value is the name of one of the constraints defined in grails.gorm.default.constraints
. Despite the name of the configuration setting, you can reference these shared constraints from any validateable class, such as command objects.
shared
引数にはgrails.gorm.default.constraints
内に定義した制約の名前の1つを指定していることに注目してください。
このように設定ファイル内の名前であるにもかかわらず、コマンドオブジェクトのようなバリデーション可能なクラスから共有された制約を参照できます。'*'
に関連した制約(上記の例ではnullable
とsize
)はバリデーション可能なクラス内のすべてのプロパティへ適用されます。
これらのデフォルト設定はバリデーション可能なクラス内で宣言する制約によって上書き可能です。Importing Constraints
制約をインポートする
class User { String firstName String lastName String passwordHashstatic constraints = { firstName blank: false, nullable: false lastName blank: false, nullable: false passwordHash blank: false, nullable: false } }
UserCommand
, that shares some of the properties of the domain class and the corresponding constraints. You do this with the importFrom()
method:
importFrom()
メソッドで実現できます:class UserCommand { String firstName String lastName String password String confirmPasswordstatic constraints = { importFrom User
password blank: false, nullable: false confirmPassword blank: false, nullable: false } }
User
domain class and apply them to UserCommand
. The import will ignore any constraints in the source class (User
) that don't have corresponding properties in the importing class (UserCommand
). In the above example, only the 'firstName' and 'lastName' constraints will be imported into UserCommand
because those are the only properties shared by the two classes.
User
ドメインクラスからすべての制約をインポートし、UserCommand
へこれらの制約を適用します。
このインポートは、インポート先のクラス(UserCommand
)に関係がないプロパティの場合、インポート元のクラス(User
)内のそのプロパティの制約を無視します。
上記の例では、firstName
とlastName
のみが両方のクラスで共有されてるため、これらの制約のみがUserCommand
へインポートされます。include
and exclude
arguments. Both of these accept a list of simple or regular expression strings that are matched against the property names in the source constraints. So for example, if you only wanted to import the 'lastName' constraint you would use:
include
とexclude
の引数が使えます。
両者ともに、インポート元の制約のプロパティ名に一致する単なる文字列、または正規表現文字列のリストを受け取ります。
例えば、lastName
制約だけをインポートしたい場合は以下のように使います:… static constraints = { importFrom User, include: ["lastName"] … }
Name
で終わるすべての制約をインポートしたい場合:…
static constraints = {
importFrom User, include: [/.*Name/]
…
}
exclude
does the reverse, specifying which constraints should not be imported.
exclude
はこの逆で、インポートすべきでない制約を指定します。
10.4 クライアントサイドバリデーション
Displaying Errors
エラーを表示する
<g:renderErrors bean="${user}" />
<g:hasErrors bean="${user}"> <ul> <g:eachError var="err" bean="${user}"> <li>${err}</li> </g:eachError> </ul> </g:hasErrors>
Highlighting Errors
エラーをハイライトする
<div class='value ${hasErrors(bean:user,field:'login','errors')}'> <input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/> </div>
login
field of the user
bean has any errors and if so it adds an errors
CSS class to the div
, allowing you to use CSS rules to highlight the div
.
user
ビーンのlogin
フィールドにエラーがあるかどうかをチェックし、エラーがある場合にはdiv
にerros
というCSSのクラスを追加するので、dev
をハイライトするCSSルールが使えるようになります。Retrieving Input Values
入力値を取得する
<input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/>
FieldError
in the User
bean and if there is obtain the originally input value for the login
field.
User
ビーン内にFieldError
が存在するかチェックし、もし存在する場合はlogin
フィールドに対する元の入力値を取得します。
10.5 バリデーションの国際化
Constraints and Message Codes
制約とメッセージコード
package com.mycompany.myappclass User { ...
static constraints = { login size: 5..15, blank: false, unique: true password size: 5..15, blank: false email email: true, blank: false age min: 18 } }
[Class Name].[Property Name].[Constraint Code]
blank
constraint this would be user.login.blank
so you would need a message such as the following in your grails-app/i18n/messages.properties
file:
blank
制約の場合はuser.login.blank
となり、grails-app/i18n/messages.properties
ファイル内に以下のようなメッセージが必要です:user.login.blank=Your login name must be specified!
com.mycompany.myapp.User.login.blank
はuser.login.blank
よりも先に使われます。
これによりドメインクラスのメッセージコードがプラグインと競合した場合でも競合を回避できます。Displaying Messages
メッセージを表示する
<g:hasErrors bean="${user}"> <ul> <g:eachError var="err" bean="${user}"> <li><g:message error="${err}" /></li> </g:eachError> </ul> </g:hasErrors>
error
argument to read the message for the given error.
error
引数を組み合わせて使用しています。10.6 コマンドオブジェクト、ドメインクラス以外のバリデーション
constraints
property in the class (as described above) and then telling the framework about them. It is important that the application register the validateable classes with the framework. Simply defining the constraints
property is not sufficient.
constraints
プロパティを定義し、それからフレームワークにこのクラスを教えてあげることで、バリデーション可能にすることができます。
アプリケーション側からバリデーション可能なクラスをフレームワークに登録するということが重要です。
単にconstraints
プロパティを定義しただけでは十分ではありません。The Validateable Annotation
Validateableアノテーション
constraints
property and are annotated with @Validateable can be made validateable by the framework. Consider this example:
constraints
プロパティを定義し、@Validateable
を付与することでフレームワークによってバリデーション可能となります。
例えば:// src/groovy/com/mycompany/myapp/User.groovy package com.mycompany.myappimport grails.validation.Validateable
@Validateable class User { ...
static constraints = { login size: 5..15, blank: false, unique: true password size: 5..15, blank: false email email: true, blank: false age min: 18 } }
Registering Validateable Classes
バリデーション可能なクラスの登録
Validateable, it may still be made validateable by the framework. The steps required to do this are to define the static
constraints property in the class (as described above) and then telling the framework about the class by assigning a value to the
grails.validateable.classes property in
Config.groovy@:
@Validateable
が付与されていなくても、フレームワークによってバリデーション可能になっている場合があります。
アノテーションなしでバリデーション可能にするには、(前述したように)そのクラス内で静的なconstraints
プロパティを定義し、それからConfig.groovy
内のgrails.validateable.classes
プロパティに値を設定してフレームワークにこのクラスを教えてあげる必要があります:grails.validateable.classes = [com.mycompany.myapp.User, com.mycompany.dto.Account]
11 サービスレイヤー
サービスを作成する Creating a Service
grails create-service helloworld.simple
If no package is specified with the create-service script, Grails automatically uses the application name as the package name.create-serviceスクリプト実行した際にパッケージ名を指定しなかった場合は、アプリケーション名をパッケージ名として使用します。
grails-app/services/helloworld/SimpleService.groovy
. A service's name ends with the convention Service
, other than that a service is a plain Groovy class:grails-app/services/helloworld/SimpleService.groovy
というサービスが作成されます。サービスの名前は、規約でService
で終わることになっており、作成されるサービスは、普通のGroovyクラスですpackage helloworldclass SimpleService { }
11.1 断定的なトランザクション
デフォルトの宣言的トランザクション Default Declarative Transactions
transactional
property to false
:transactional
プロパティにfalse
を設定します:class CountryService { static transactional = false }
true
to make it clear that the service is intentionally transactional.Warning: dependency injection is the only way that declarative transactions work. You will not get a transactional service if you use the警告:依存性の注入は、宣言的トランザクションが機能する唯一の方法です。new
operator such asnew BookService()
new BookService()
のようにnew
演算子を使用した場合、トランザクションなサービスを取得するできません。
RuntimeException
) or an Error
. The propagation level of the transaction is by default set to PROPAGATION_REQUIRED.Checked exceptions do not roll back transactions. Even though Groovy blurs the distinction between checked and unchecked exceptions, Spring isn't aware of this and its default behaviour is used, so it's important to understand the distinction between checked and unchecked exceptions.
カスタムトランザクションの設定 Custom Transaction Configuration
Transactional
annotation for cases where you need more fine-grained control over transactions at a per-method level or need specify an alternative propagation level.Transactional
アノテーションもフルサポートしています:Annotating a service method withTransactional
disables the default Grails transactional behavior for that service (in the same way that addingtransactional=false
does) so if you use any annotations you must annotate all methods that require transactions.Transactional
アノテーションをメソッドに指定すると、デフォルトの書式(transactional=false
での定義)でのトランザクションは無効になります。アノテーションを使用する場合は、トランザクションが必要な全てのメソッドに定義する必要があります。
listBooks
uses a read-only transaction, updateBook
uses a default read-write transaction, and deleteBook
is not transactional (probably not a good idea given its name).listBooks
がread-onlyトランザクションを使用、updateBook
がデフォルトのread-writeトランザクションを使用、deleteBook
にはトランザクションは指定されていません(このメソッドの名前的に良くはありませんが)。
import org.springframework.transaction.annotation.Transactionalclass BookService {
@Transactional(readOnly = true) def listBooks() { Book.list() }
@Transactional def updateBook() { // … }
def deleteBook() { // … } }
transactional=true
):transactional=true
がデフォルトなので):import org.springframework.transaction.annotation.Transactional@Transactional class BookService {
def listBooks() { Book.list() }
def updateBook() { // … }
def deleteBook() { // … } }
listBooks
method overrides this to use a read-only transaction:listBooks
メソッド以外の、全メソッドがread-writeトランザクションになります(クラスレベルのアノテーションの定義によって)。import org.springframework.transaction.annotation.Transactional@Transactional class BookService {
@Transactional(readOnly = true) def listBooks() { Book.list() }
def updateBook() { // … }
def deleteBook() { // … } }
updateBook
and deleteBook
aren't annotated in this example, they inherit the configuration from the class-level annotation.updateBook
とdeleteBook
はアノテーション指定されていませんが、クラスレベルアノテーションの定義が受け継がれます。Transactional
; just specify the annotation as needed and Grails will detect them up automatically.Transactional
を使用するための特別な定義は必要有りません。必要なアノテーションを記述すればGrailsが自動的に認識します。
11.1.1 トランザクションロールバックとセッション
Understanding Transactions and the Hibernate Session
When using transactions there are important considerations you must take into account with regards to how the underlying persistence session is handled by Hibernate. When a transaction is rolled back the Hibernate session used by GORM is cleared. This means any objects within the session become detached and accessing uninitialized lazy-loaded collections will lead to LazyInitializationException
s.
To understand why it is important that the Hibernate session is cleared. Consider the following example:
class Author { String name Integer agestatic hasMany = [books: Book] }
If you were to save two authors using consecutive transactions as follows:
Author.withTransaction { status -> new Author(name: "Stephen King", age: 40).save() status.setRollbackOnly() }Author.withTransaction { status -> new Author(name: "Stephen King", age: 40).save() }
Only the second author would be saved since the first transaction rolls back the author save()
by clearing the Hibernate session. If the Hibernate session were not cleared then both author instances would be persisted and it would lead to very unexpected results.
It can, however, be frustrating to get LazyInitializationException
s due to the session being cleared.
For example, consider the following example:
class AuthorService {void updateAge(id, int age) { def author = Author.get(id) author.age = age if (author.isTooOld()) { throw new AuthorException("too old", author) } } }
class AuthorController {def authorService
def updateAge() { try { authorService.updateAge(params.id, params.int("age")) } catch(e) { render "Author books ${e.author.books}" } } }
In the above example the transaction will be rolled back if the Author
's age exceeds the maximum value defined in the isTooOld()
method by throwing an AuthorException
. The AuthorException
references the author but when the books
association is accessed a LazyInitializationException
will be thrown because the underlying Hibernate session has been cleared.
To solve this problem you have a number of options. One is to ensure you query eagerly to get the data you will need:
class AuthorService { … void updateAge(id, int age) { def author = Author.findById(id, [fetch:[books:"eager"]]) ...
In this example the books
association will be queried when retrieving the Author
.
This is the optimal solution as it requires fewer queries then the following suggested solutions.
Another solution is to redirect the request after a transaction rollback:
class AuthorController {AuthorService authorService
def updateAge() { try { authorService.updateAge(params.id, params.int("age")) } catch(e) { flash.message "Can't update age" redirect action:"show", id:params.id } } }
In this case a new request will deal with retrieving the Author
again. And, finally a third solution is to retrieve the data for the Author
again to make sure the session remains in the correct state:
class AuthorController {def authorService
def updateAge() { try { authorService.updateAge(params.id, params.int("age")) } catch(e) { def author = Author.read(params.id) render "Author books ${author.books}" } } }
Validation Errors and Rollback
A common use case is to rollback a transaction if there are validation errors. For example consider this service:
import grails.validation.ValidationExceptionclass AuthorService {
void updateAge(id, int age) { def author = Author.get(id) author.age = age if (!author.validate()) { throw new ValidationException("Author is not valid", author.errors) } } }
To re-render the same view that a transaction was rolled back in you can re-associate the errors with a refreshed instance before rendering:
import grails.validation.ValidationExceptionclass AuthorController {
def authorService
def updateAge() { try { authorService.updateAge(params.id, params.int("age")) } catch (ValidationException e) { def author = Author.read(params.id) author.errors = e.errors render view: "edit", model: [author:author] } } }
11.2 サービスのスコープ
prototype
- A new service is created every time it is injected into another classrequest
- A new service will be created per requestflash
- A new service will be created for the current and next request onlyflow
- In web flows the service will exist for the scope of the flowconversation
- In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flowssession
- A service is created for the scope of a user sessionsingleton
(default) - Only one instance of the service ever exists
prototype
- クラスへの注入時にサービスが生成されるrequest
- リクエスト毎にサービスが生成されるflash
- 現在とその次のリクエスト用にサービスが生成されるflow
- フローの開始から終了まてのサービス(サブフロー含まず)conversation
- フローの開始から終了まてのサービス(サブフロー含む)session
- ユーザセッション毎にサービスが生成されるsingleton
(デフォルト) - サービスが1つのみ生成される
If your service isサービスのスコープがflash
,flow
orconversation
scoped it must implementjava.io.Serializable
and can only be used in the context of a Web Flowflash
、flow
あるいはconversation
の場合、java.io.Serializableを実装する必要があり、Webフローのコンテキストの中でだけ使うことができます。
static scope = "flow"
11.3 依存注入とサービス
依存性の注入の基本 Dependency Injection Basics
BookService
, if you define a property called bookService
in a controller as follows:BookService
というサービスが与えられた場合、次のようにコントローラの中にbookService
という名前のプロパティを配置します:class BookController { def bookService … }
class AuthorService { BookService bookService }
NOTE: Normally the property name is generated by lower casing the first letter of the type. For example, an instance of the注:通常、プロパティ名は、型の最初の文字を小文字のにして生成します。たとえば、BookService
class would map to a property namedbookService
.BookService
クラスのインスタンスは、bookService
という名前のプロパティにマップされます。To be consistent with standard JavaBean conventions, if the first 2 letters of the class name are upper case, the property name is the same as the class name. For example, the property name of the標準のJavaBean規約と整合をとるため、クラス名の最初の2文字が大文字の場合、プロパティ名はクラス名と同じになります。たとえばJDBCHelperService
class would beJDBCHelperService
, notjDBCHelperService
orjdbcHelperService
.JDBCHelperService
クラスは、jDBCHelperService
またjdbcHelperService
では無く、JDBCHelperService
という名前のプロパティにマップされます。See section 8.8 of the JavaBean specification for more information on de-capitalization rules.小文字への変換規則の詳細については、JavaBeanの仕様のセクション8.8を参照してください。
依存性注入とサービス Dependency Injection and Services
AuthorService
that needed to use the BookService
, declaring the AuthorService
as follows would allow that:AuthorService
がBookService
使用する場合、 次のようにAuthorService
を宣言することで使用することができます:class AuthorService { def bookService }
依存性注入とドメインクラス/タグライブラリ Dependency Injection and Domain Classes / Tag Libraries
class Book { … def bookServicedef buyBook() { bookService.buyBook(this) } }
Service Bean Names
The default bean name which is associated with a service can be problematic if there are multiple services with the same name defined in different packages. For example consider the situation where an application defines a service class named com.demo.ReportingService
and the application uses a plugin named ReportingUtilities
and that plugin provides a service class named com.reporting.util.ReportingService
. The default bean name for each of those would be reportingService
so they would conflict with each other. Grails manages this by changing the default bean name for services provided by plugins by prefixing the bean name with the plugin name. In the scenario described above the reportingService
bean would be an instance of the com.demo.ReportingService
class defined in the application and the reportingUtilitiesReportingService
bean would be an instance of the com.reporting.util.ReportingService
class provided by the ReportingUtilities
plugin. For all service beans provided by plugins, if there are no other services with the same name within the application or other plugins in the application then a bean alias will be created which does not include the plugin name and that alias points to the bean referred to by the name that does include the plugin name prefix. For example, if the ReportingUtilities
plugin provides a service named com.reporting.util.AuthorService
and there is no other AuthorService
in the application or in any of the plugins that the application is using then there will be a bean named reportingUtilitiesAuthorService
which is an instance of this com.reporting.util.AuthorService
class and there will be a bean alias defined in the context named authorService
which points to that same bean.
11.4 Javaからサービスを使う
grails-app/services
directory. The reason this is important is that it is not possible to import classes into Java from the default package (the package used when no package declaration is present). So for example the BookService
below cannot be used from Java as it stands:grails-app/services
ディレクトリ下で、パッケージの中にサービスを移動することです。これが重要な手順である理由は、デフォルトパッケージ(パッケージの宣言がない場合に使用されるパッケージ)からJavaにクラスをインポートできないからです。したがって、たとえば以下のBookService
は、そのままではJavaから使用できません:class BookService { void buyBook(Book book) { // logic } }
grails-app/services/bookstore
and then modifying the package declaration:grails-app/services/bookstore
といったサブディレクトリの中にクラスを移動し、パッケージ宣言を修正することで、是正できます:package bookstoreclass BookService { void buyBook(Book book) { // logic } }
package bookstoreinterface BookStore { void buyBook(Book book) }
class BookService implements bookstore.BookStore {
void buyBook(Book b) {
// logic
}
}
src/java
directory and add a setter that uses the type and the name of the bean in Spring:src/java
ディレクトリのパッケージにJavaクラスを作ることができ、Springビーンの型と名前を使うセッターを提供することができます:// src/java/bookstore/BookConsumer.java package bookstore;public class BookConsumer {
private BookStore store;
public void setBookStore(BookStore storeInstance) { this.store = storeInstance; } … }
grails-app/conf/spring/resources.xml
(for more information see the section on Grails and Spring):grails-app/conf/spring/resources.xml
の中にSpringビーンとしてJavaクラスを設定することができます(詳細は、GrailsとSpringセクションを参照してください)<bean id="bookConsumer" class="bookstore.BookConsumer"> <property name="bookStore" ref="bookService" /> </bean>
grails-app/conf/spring/resources.groovy
:grails-app/conf/spring/resources.groovy
に:import bookstore.BookConsumerbeans = { bookConsumer(BookConsumer) { bookStore = ref("bookService") } }
12 テスト
Grails 1.3.x and below used the grails.test.GrailsUnitTestCase
class hierarchy for testing in a JUnit 3 style. Grails 2.0.x and above deprecates these test harnesses in favour of mixins that can be applied to a range of different kinds of tests (JUnit 3, Junit 4, Spock etc.) without subclassing
Grails 1.3.X以下のバージョンでは、JUnit 3スタイルのテストのためにgrails.test.GrailsUnitTestCase
のクラスを継承するようになっていましたが、Grails 2.0.X 以上のバージョンではサブクラスを作ることなく異なる種類のテスト(Junit 3, Junit4, Spock など)を実施可能なMixinsベースのテストを推奨しています。
create-*
and generate-*
commands create unit
or integration
tests automatically. For example if you run the create-controller command as follows:create-*
やgenerate-*
のコマンドはunit
もしくはintegration
テストを自動的に生成します。例えば、create-controllerコマンドを以下のように実行したとします。:grails create-controller com.acme.app.simple
grails-app/controllers/com/acme/app/SimpleController.groovy
, and also a unit test at test/unit/com/acme/app/SimpleControllerTests.groovy
. What Grails won't do however is populate the logic inside the test! That is left up to you.grails-app/controllers/com/acme/app/SimpleController.groovy
にコントローラを、test/unit/com/acme/app/SimpleControllerTests.groovy
にユニットテストを作ります。しかしながら、Grailsはテストの中のロジックは作成しません!それはあなたに任されています。The default class name suffix isTests
but as of Grails 1.2.2, the suffix ofTest
is also supported.
デフォルトのクラス名の最後にはTests
を付けます。しかし、Grails 1.2.2からはTest
のサフィックスもサポートしています。
テストの実行
grails test-app
------------------------------------------------------- Running Unit Tests… Running test FooTests...FAILURE Unit Tests Completed in 464ms … -------------------------------------------------------Tests failed: 0 errors, 1 failures
You can force a clean before running tests by passing-clean
to thetest-app
command.
test-app
コマンドに-clean
を付与することにより、テスト実行前に強制的にテスト実行環境をクリーンにすることができます。
target/test-reports
directory, along with the original XML files. The HTML reports are generally the best ones to look at.target/test-reports
ディレクトリにオリジナルのXMLファイルとともにプレインテキストとHTMLのテストレポートの両方を出力します。最も見栄えがよいのはHTMLレポートです。open test-report
unit
テストを実行できます。テストを指定する
SimpleController
you would run:SimpleController
と名付けられたコントローラの全てのテストを実行したい場合には以下のように指定します。:grails test-app SimpleController
SimpleController
. Wildcards can be used...SimpleController
という名前に対応する全てのテストを実行します。ワイルドカードを利用することも可能です。:grails test-app *Controller
Controller
. Package names can optionally be specified...Controller
でクラス名が終わる全てのクラスのテストを実行します。パッケージ名も指定可能です。grails test-app some.org.*Controller
grails test-app some.org.*
grails test-app some.org.**.*
grails test-app SimpleController.testLogin
testLogin
test in the SimpleController
tests. You can specify as many patterns in combination as you like...SimpleController
テストの中にあるtestLogin
テストを実行します。いくつかのパターンを組合せて好きなように指定できます。grails test-app some.org.* SimpleController.testLogin BookController
テスト種別とテストフェーズの条件によるテストの指定
phase:type
syntax.テストフェーズ:テスト種別
の記法により テスト種別 と テストフェーズ を条件として指定できます。Grails organises tests by phase and by type. A test phase relates to the state of the Grails application during the tests, and the type relates to the testing mechanism.Grails comes with support for 4 test phases (
unit
,integration
,functional
andother
) and JUnit test types for theunit
andintegration
phases. These test types have the same name as the phase.Testing plugins may provide new test phases or new test types for existing phases. Refer to the plugin documentation.
Grailsはテストフェーズとテスト種別によりテストを体系化しています。テストフェーズはGrailsアプリケーションにおけるどの状態のテストを行っているかを表しており、テスト種別はテストを行う機構に関連しています。Grailsは4つのテストフェーズ(
unit
,integration
,functional
そしてother
)とunit
とintegration
の各テストフェーズに対応したJUnitのテスト種別をサポートしています。これらのテスト種別はそのテストフェーズと同じ名前になっています。テストプラグインにより既存のテストフェーズに新しいテストフェーズもしくはテスト種別を追加することができます。詳しくはプラグインのドキュメントを参照してください。
integration
tests you can run:integration
テストを実行するには以下のように実行します:grails test-app integration:integration
phase
and type
are optional. Their absence acts as a wildcard. The following command will run all test types in the unit
phase:テストフェーズ
とテスト種別
の指定は任意です。もし指定をしなかった場合には全てが該当します。以下のコマンドではunit
テストフェーズの全てのテスト種別のテストを実行します。:grails test-app unit:
spock
test type to the unit
, integration
and functional
phases. To run all spock tests in all phases you would run the following:spock
テスト種別がunit
、integration
そしてfunctional
テストフェーズで使えるようになります。全てのテストフェーズで全てのspock
テストを実行するには次のように実行します。:grails test-app :spock
functional
phase you would run...functional
フェーズの全てのspock
テストを実行するには次のように実行します。grails test-app functional:spock
grails test-app unit:spock integration:spock
テスト種別とテストフェーズを用いたテストの指定
grails test-app integration: unit: some.org.**.*
integration
and unit
phases that are in the package some.org
or a subpackage.some.org
のパッケージかサブパッケージの中でintegration
とunit
フェーズの全てのテストが実行されるでしょう。
12.1 ユニットテスト
Unitテストは"単体"レベルのテストです。具体的には、環境周りを考慮せずに個々のメソッドやブロック単位で行うテストのことです。Unitテストは基本的にデータベース、ネットワーク接続、ファイルなどのI/Oを必要とする物理リソースを必要としません。素早いフィードバックを得られるように、Unitテストの実行時間はできる限り短くしてください。
The Test Mixins
テストMixin
Grails 2.0以降、MixinのUnitテストライブラリがGrailsによって提供されており、代表的なJUnit 3、JUnit 4、Spockを使用したテストの実行をサポートします。以下の節では、Mixinの使い方について記載しています。
The previous JUnit 3-style GrailsUnitTestCase
class hierarchy is still present in Grails for backwards compatibility, but is now deprecated. The previous documentation on the subject can be found in the Grails 1.3.x documentation
以前のGrailsUnitTestCase
クラスを継承するJUnit 3スタイルは、下位バージョンとの互換性のためにGrailsにまだ存在しています。しかし今は非推奨です。過去のドキュメントはGrails 1.3.x ドキュメンテーションで見つけることができます。
Grailsは自動でテストクラスをインポートするため、全てのテストクラスをインポートしなくても問題ありません。しかし、IDEでテストクラスを探せないことがあるかもしれないので、下記にそれらすべてのテストクラスを列挙します。
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
Test Mixin Basics
テストMixinの基本
TestFor
annotation in combination with the Mock
annotation for mocking collaborators. For example, to test a controller and associated domains you would define the following:
ほとんどのテストは、モックを使用するためMock
アノテーションとTestFor
アノテーションを組み合わせて使用します。例えば、コントローラーとドメインをテストするためには次のように定義します。
@TestFor(BookController) @Mock([Book, Author, BookService])
TestFor
annotation defines the class under test and will automatically create a field for the type of class under test. For example in the above case a "controller" field will be present, however if TestFor
was defined for a service a "service" field would be created and so on.
TestFor
アノテーションは、テスト対象のクラスを定義することで自動的にクラスタイプのフィールドを生成します。例えば、上記の場合、"controller"フィールドを生成します。また、もしTestFor
にサービスが定義されている場合、"service"フィールドが生成されます。
Mock
annotation creates mock version of any collaborators. There is an in-memory implementation of GORM that will simulate most interactions with the GORM API. For those interactions that are not automatically mocked you can use the built in support for defining mocks and stubs programmatically. For example:
Mock
アノテーションは複数の種類のモックを生成します。ほとんどのGORM APIの振る舞いをシミュレートするインメモリのGORM実装があります。自動でモック化されない振る舞いに対しては、ビルトインされているモック、スタブの作成機能が使用できます。例えば、次の通りです。
void testSearch() { def control = mockFor(SearchService) control.demand.searchWeb { String q -> ['mock results'] } control.demand.static.logResults { List results -> } controller.searchService = control.createMock() controller.search()assert controller.response.text.contains "Found 1 results" }
12.1.1 コントローラのユニットテスト
The Basics
基本
grails.test.mixin.TestFor
annotation to unit test controllers. Using TestFor
in this manner activates the grails.test.mixin.web.ControllerUnitTestMixin
and its associated API. For example:
コントローラUnitテストには、grails.test.mixin.TestFor
アノテーションを使用します。このようにTestFor
を使用することで、grails.test.mixin.web.ControllerUnitTestMixin
とその関連APIが有効になります。
import grails.test.mixin.TestFor@TestFor(SimpleController) class SimpleControllerTests { void testSomething() {
} }
TestFor
annotation to a controller causes a new controller
field to be automatically created for the controller under test.
TestFor
アノテーションにコントローラを追加することにより、controller
フィールドにテスト対象のコントローラが自動的に生成されます。
The TestFor
annotation will also automatically annotate any public methods starting with "test" with JUnit 4's @Test annotation. If any of your test method don't start with "test" just add this manually
TestFor
アノテーションは"test"から始まるパブリックなメソッドに自動的にJUnit4のTestアノテーションを付与します。もしテストメソッドが"test"で始まらない場合は
Testアノテーションを手動で付与してください。
最もシンプルなHello World形式のテストは次の通りです。
// Test class
class SimpleController {
def hello() {
render "hello"
}
}
void testHello() { controller.hello()assert response.text == 'hello' }
response
object is an instance of GrailsMockHttpServletResponse
(from the package org.codehaus.groovy.grails.plugins.testing
) which extends Spring's MockHttpServletResponse
class and has a number of useful methods for inspecting the state of the response.
response
オブジェクトは、GrailsMockHttpServletResponse
(org.codehaus.groovy.grails.plugins.testing
パッケージに含まれている)のインスタンスです。SpringのMockHttpServletResponse
クラスを継承しており、レスポンスの状態を調べる便利なメソッドを定義しています。
redirectedUrl
property:
例えば、リダイレクトをテストするにはredirectedUrl
プロパティを使用できます。
// Test class class SimpleController { def index() { redirect action: 'hello' } … }
void testIndex() { controller.index()assert response.redirectedUrl == '/simple/hello' }
params
variable:
ほとんどのアクションはリクエストに設定されたパラメータを使用します。例えば、'sort'、'max'、'offset'といったパラメータが一般的です。これらのパラメータをテストで利用するにはparams
変数に値を代入するだけで簡単に設定できます。
void testList() { params.sort = "name" params.max = 20 params.offset = 0controller.list() … }
method
property of the mock request:
リクエストのmethod
プロパティにリクエストタイプを設定することにより、リクエストタイプ毎のコントローラのアクションを確認できます。
void testSave() {
request.method = "POST"
controller.save()
…
}
リクエストタイプに応じてアクションが違った挙動をする場合、これは非常に重要です。さらに、次のようにAjaxとしてリクエストを作ることもできます。
void testGetPage() {
request.method = "POST"
request.makeAjaxRequest()
controller.getPage()
…
}
xhr
property on the request.
テスト対象コードのリクエストでxhr
プロパティを使用してたとしても、これを実行するだけです。
Testing View Rendering
ビューのレンダリングテスト
modelAndView
property (an instance of org.springframework.web.servlet.ModelAndView
) or you can use the view
and model
properties provided by the mixin:
コントローラのmodelAndView
プロパティ(org.springframework.web.servlet.ModelAndView
のインスタンス)、または、Mixinで提供されているview
とmodel
プロパティを使用することにより、ビューのレンダリングをテストすることができます。
// Test class class SimpleController { def home() { render view: "homePage", model: [title: "Hello World"] } … }
void testIndex() { controller.home()assert view == "/simple/homePage" assert model.title == "Hello World" }
viewの文字列は絶対パスであることに注意してください。これは、'/'から始まり、動作するコントローラの名前から決まるディレクトリ名などがパスとして含まれます。
Testing Template Rendering
テンプレートレンダリングテスト
ModelAndView
hence it requires a different approach to testing.
テンプレートのレンダリングはModelAndView
を返すのではなく、レスポンスにテンプレートの内容を直接書き込みます。そのため、ビューのレンダリングとは異なるテストのアプローチが必要になります。
次のコントローラアクションを見てください。
class SimpleController {
def display() {
render template:"snippet"
}
}
grails-app/views/simple/_snippet.gsp
. You can test this as follows:
この例では、コントローラはgrails-app/views/simple/_snippet.gsp
にあるテンプレートを探します。そして、次のようにテストをします。
void testDisplay() { controller.display() assert response.text == 'contents of template' }
テンプレートをレンダリングしたくない場合にも、テストでは実際にテンプレートがレンダリングされます。このような場合はGroovy Pagesのモックが使用できます。
void testDisplay() { views['/simple/_snippet.gsp'] = 'mock contents' controller.display() assert response.text == 'mock contents' }
Testing Actions Which Return A Map
マップを返すアクションをテスト
java.util.Map
that Map
may be inspected directly to assert that it contains the expected data:
コントローラアクションがjava.util.Map
を返す場合は、Map
に期待したデータが含まれているか直接検証できます。
class SimpleController { def showBookDetails() { [title: 'The Nature Of Necessity', author: 'Alvin Plantinga'] } }
import grails.test.mixin.*@TestFor(SimpleController) class SimpleControllerTests {
void testShowBookDetails() { def model = controller.showBookDetails()
assert model.author == 'Alvin Plantinga' } }
Testing XML and JSON Responses
XMLとJSONレスポンスのテスト
XMLとJSONのレスポンスもまた、直接レスポンスに書き込まれます。Grailsのモック機構は、XMLとJSONのレスポンスをテストするために便利な機能をいくつか提供しています。
def renderXml() { render(contentType:"text/xml") { book(title:"Great") } }
xml
property of the response:
次の例は、レスポンスのxml
プロパティを使ってテストしています。
void testRenderXml() { controller.renderXml() assert "<book title='Great'/>" == response.text assert "Great" == response.xml.@title.text() }
xml
property is a parsed result from Groovy's XmlSlurper class which is very convenient for parsing XML.
xml
プロパティは、XMLをパースするためにとても便利なGroovyのXmlSlurper でパースされた結果です。
json
property:
json
プロパティを使うだけで、JSONレスポンスのテストもかなり似ています。
// controller action def renderJson() { render(contentType:"application/json") { book = "Great" } }
// test void testRenderJson() {controller.renderJson()
assert '{"book":"Great"}' == response.text assert "Great" == response.json.book }
json
property is an instance of org.codehaus.groovy.grails.web.json.JSONElement
which is a map-like structure that is useful for parsing JSON responses.
json
プロパティは、JSONレスポンスをパースするために便利なorg.codehaus.groovy.grails.web.json.JSONElement
のインスタンスでマップライクな構造をもっています。
Testing XML and JSON Requests
XMLとJSONリクエストのテスト
Grailsは、入力されるXMLとJSONパケットを自動的にパースするためのいろいろな便利な方法を提供しています。例えば、入力されるJSONかXMLリクエストをGrailsのデータバインディングを使ってバインドできます。
def consumeBook() { def b = new Book(params['book'])render b.title }
xml
or json
properties. For example the above action can be tested by specifying a String containing the XML:
次のテストでは、xml
やjson
プロパティを用いてXMLやJSONリクエストを設定しています。例えば、上記のアクションはXMLの文字列を設定することによってテストができます。
void testConsumeBookXml() { request.xml = '<book><title>The Shining</title></book>' controller.consumeBook()assert response.text == 'The Shining' }
もしくは、ドメインインスタンスを設定することで、適切なXMLリクエストに自動変換してテストをします。
void testConsumeBookXml() { request.xml = new Book(title:"The Shining") controller.consumeBook()assert response.text == 'The Shining' }
JSONリクエストでも同じようにテストできます。
void testConsumeBookJson() { request.json = new Book(title:"The Shining") controller.consumeBook()assert response.text == 'The Shining' }
もし、Grailsのデータバインディングを使用したくない場合は、入力されるXMLまたはJSONを手動でパースする必要がありますが、このような場合も同じようにテストできます。次のコントローラアクションを見てください。
def consume() { request.withFormat { xml { render request.XML.@title } json { render request.JSON.title } } }
XMLリクエストをテストするためには、XMLの文字列を設定します。
void testConsumeXml() { request.xml = '<book title="The Stand" />'controller.consume()
assert response.text == 'The Stand' }
もちろん、同じことがJSONでもできます。
void testConsumeJson() { request.json = '{title:"The Stand"}' controller.consume()assert response.text == 'The Stand' }
Testing Spring Beans
Springビーンのテスト
TestFor
only a subset of the Spring beans available to a running Grails application are available. If you wish to make additional beans available you can do so with the defineBeans
method of GrailsUnitTestMixin
:
TestFor
を使用した場合は、Grailsアプリケーションを実行するのに必要なSpringビーンのサブセットだけが利用できます。もし、利用できるビーンを追加したい場合は、GrailsUnitTestMixin
のdefineBeans
メソッドを使うことにより、ビーンを追加できます。
class SimpleController { SimpleService simpleService def hello() { render simpleService.sayHello() } }
void testBeanWiring() { defineBeans { simpleService(SimpleService) }controller.hello()
assert response.text == "Hello World" }
コントローラは実行中のGrailsアプリケーションのように、Springによって自動的にビーンが注入されます。もしコントローラを後でインスタンス化した場合も自動的に注入されます。
void testAutowiringViaNew() { defineBeans { simpleService(SimpleService) }def controller1 = new SimpleController() def controller2 = new SimpleController()
assert controller1.simpleService != null assert controller2.simpleService != null }
Testing Mime Type Handling
MIME Typeの制御のテスト
withFormat
method quite simply by setting the response's format
attribute:
MIME Typeの制御とwithFormat
メソッドは、レスポンスのformat
属性を設定することにより簡単にテストができます。
// controller action
def sayHello() {
def data = [Hello:"World"]
withFormat {
xml { render data as XML }
html data
}
}
// test void testSayHello() { response.format = 'xml' controller.sayHello()String expected = '<?xml version="1.0" encoding="UTF-8"?>' + '<map><entry key="Hello">World</entry></map>'
assert expected == response.text }
Testing Duplicate Form Submissions
フォームの2重送信テスト
フォームの2重送信のテストは少し複雑になります。例えば、次のようなフォームを処理するアクションがあるとします。
def handleForm() { withForm { render "Good" }.invalidToken { render "Bad" } }
ここでフォームの送信が成功する場合と、2重送信となる場合のロジックを検証したいとします。2重送信となる場合のテストは、単にコントローラをすることで簡単に実行できます。
void testDuplicateFormSubmission() {
controller.handleForm()
assert "Bad" == response.text
}
SynchronizerToken
:
フォームの送信が成功する場合のテストは適切なSynchronizerToken
が必要となります。
import org.codehaus.groovy.grails.web.servlet.mvc.SynchronizerToken ...void testValidFormSubmission() { def tokenHolder = SynchronizerTokensHolder.store(session)
params[SynchronizerTokensHolder.TOKEN_URI] = '/controller/handleForm' params[SynchronizerTokensHolder.TOKEN_KEY] = tokenHolder.generateToken(params[SynchronizerTokensHolder.TOKEN_URI])
controller.handleForm() assert "Good" == response.text }
もし、有効/無効のリクエストを両方ともテストしたい場合、コントローラのメソッド実行の間で、レスポンスをリセットしてください。
controller.handleForm() // first execution … response.reset() … controller.handleForm() // second execution
Testing File Upload
ファイルアップロードのテスト
GrailsMockMultipartFile
class to test file uploads. For example consider the following controller action:
ファイルアップロードをテストするためには、GrailsMockMultipartFile
クラスを使います。例えば、次のコントローラアクションを見てください。
def uploadFile() { MultipartFile file = request.getFile("myFile") file.transferTo(new File("/local/disk/myFile")) }
GrailsMockMultipartFile
with the request:
このアクションをテストするには、リクエストにGrailsMockMultipartFile
を設定してください。
void testFileUpload() { final file = new GrailsMockMultipartFile("myFile", "foo".bytes) request.addFile(file) controller.uploadFile()assert file.targetFileLocation.path == "/local/disk/myFile" }
GrailsMockMultipartFile
constructor arguments are the name and contents of the file. It has a mock implementation of the transferTo
method that simply records the targetFileLocation
and doesn't write to disk.
GrailsMockMultipartFile
のコンストラクタの引数はファイル名とファイルの内容です。これはtransferTo
のモック実装をもっており、ファイルには書き込まずにtargetFileLocation
として値を保持します。
Testing Command Objects
Commnadオブジェクトのテスト
mockCommandObject
method. For example consider the following action:
mockCommandObject
メソッドにはCommandオブジェクトの処理をテストするための特別な機能があります。例えば、次のアクションを見てください。
def handleCommand(SimpleCommand simple) { if (simple.hasErrors()) { render "Bad" } else { render "Good" } }
これをテストするために、次のようにCommandオブジェクトをモック化した上で、データを投入して検証してください。
void testInvalidCommand() { def cmd = mockCommandObject(SimpleCommand) cmd.name = '' // doesn't allow blank namescmd.validate() controller.handleCommand(cmd)
assert response.text == 'Bad' }
Testing Calling Tag Libraries
タグライブラリの呼び出しテスト
ControllerUnitTestMixin
, although the mechanism for testing the tag called varies from tag to tag. For example to test a call to the message
tag, add a message to the messageSource
. Consider the following action:
タグごとに必要となるテストの方法は異なりますが、タグライブラリの呼びしはControllerUnitTestMixin
を使用することでテストできます。例えば、message
タグを呼び出すテストでは、messageSource
にメッセージを加えます。次のアクションを見てください。
def showMessage() {
render g.message(code: "foo.bar")
}
これは次のようにテストをします。
void testRenderBasicTemplateWithTags() { messageSource.addMessage("foo.bar", request.locale, "Hello World")controller.showMessage()
assert response.text == "Hello World" }
12.1.2 タグライブラリのユニットテスト
The Basics
基本
grails.test.mixin.web.GroovyPageUnitTestMixin
mixin. To use the mixin declare which tag library is under test with the TestFor
annotation:
タグライブラリとGSPは、grails.test.mixin.web.GroovyPageUnitTestMixin
のMixinでテストできます。Mixinを使用するために、タグライブラリをTestFor
アノテーションの中に宣言します。
@TestFor(SimpleTagLib) class SimpleTagLibTests {}
ControllerUnitTestMixin
and the GroovyPageUnitTestMixin
using the Mock
annotation:
もし、コントローラからカスタムタグの呼び出しをテストする場合、Mock
アノテーションを使用してControllerUnitTestMixin
とGroovyPageUnitTestMixin
を組み合わせることができます。
@TestFor(SimpleController) @Mock(SimpleTagLib) class GroovyPageUnitTestMixinTests {}
Testing Custom Tags
カスタムタグのテスト
GroovyPageUnitTestMixin
class provides a mockTagLib()
method that you can use to mock a custom tag library. For example consider the following tag library:
Grailsコアのタグはテスト中に有効にする必要はありませんが、カスタムタグライブラリは有効にする必要があります。GroovyPageUnitTestMixin
クラスは、カスタムタグライブラリをモック化するために使えるmockTagLib()
メソッドを提供しています。
class SimpleTagLib {static namespace = 's'
def hello = { attrs, body -> out << "Hello ${attrs.name ?: 'World'}" }
def bye = { attrs, body -> out << "Bye ${attrs.author.name ?: 'World'}" } }
TestFor
and supplying the name of the tag library:
TestFor
を使用し、タグライブラリの名前を記載することによって、上記のタグライブラリをテストできます。
@TestFor(SimpleTagLib) class SimpleTagLibTests { void testHelloTag() { assert applyTemplate('<s:hello />') == 'Hello World' assert applyTemplate('<s:hello name="Fred" />') == 'Hello Fred' assert applyTemplate('<s:bye author="${author}" />', [author: new Author(name: 'Fred')]) == 'Bye Fred' } }
TestMixin
annotation and mock multiple tag libraries using the mockTagLib()
method:
代わりに、TestMixin
アノテーションとmockTagLib()
メソッドにより、複数のタグライブラリをモック化することができます。
@grails.test.mixin.TestMixin(GroovyPageUnitTestMixin) class MultipleTagLibraryTests {@Test void testMuliple() { mockTagLib(FirstTagLib) mockTagLib(SecondTagLib)
… } }
GroovyPageUnitTestMixin
provides convenience methods for asserting that the template output equals or matches an expected value.
GroovyPageUnitTestMixin
はテンプレート出力が期待した値と同じであることを検証するために便利なメソッドを提供しています。
@grails.test.mixin.TestMixin(GroovyPageUnitTestMixin) class MultipleTagLibraryTests {@Test void testMuliple() { mockTagLib(FirstTagLib) mockTagLib(SecondTagLib) assertOutputEquals ('Hello World', '<s:hello />') assertOutputMatches (/.*Fred.*/, '<s:hello name="Fred" />') } }
Testing View and Template Rendering
表示とテンプレートのレンダリングテスト
grails-app/views
via the render(Map)
method provided by GroovyPageUnitTestMixin
:
GroovyPageUnitTestMixin
で提供されているrender(Map)
メソッドを使ってgrails-app/views
内にあるビューとテンプレートのレンダリングをテストできます。
def result = render(template: "/simple/hello") assert result == "Hello World"
grails-app/views/simple/_hello.gsp
. Note that if the template depends on any custom tag libraries you need to call mockTagLib
as described in the previous section.
これは、grails-app/views/simple/_hello.gsp
に配置されているテンプレートをレンダリングします。もしテンプレートがいくつかのカスタムタグライブラリに依存している場合、前の節で記載したmockTagLib
を呼び出す必要があります。
12.1.3 ドメインのユニットテスト
Overview
概要
The mocking support described here is best used when testing non-domain artifacts that use domain classes, to let you focus on testing the artifact without needing a database. But when testing persistence it's best to use integration tests which configure Hibernate and use a database.
モック機能のサポートは、非ドメインクラスがドメインクラスを使用している場合に、データベースを必要とせず、テストに集中できるという意味では最適な方法です。しかし、ドメインの永続化のテストを行いたい場合はHibernateとデータベースを使用するIntegrationテストが最適な方法です。
DomainClassUnitTestMixin
. This implementation mimics the behavior of GORM against an in-memory ConcurrentHashMap
implementation. Note that this has limitations compared to a real GORM implementation. The following features of GORM for Hibernate can only be tested within an integration test:
ドメインクラスとしての振る舞いはDomainClassUnitTestMixin
を使用することで、データベースを必要とせずにテストを行うことができます。この実装はGORMの振る舞いを擬似した、メモリ上のConcurrentHashMap
です。この実装は実際のGORMの動作と比べて制限があることに注意してください。以下のHibernateに対するGORMの機能はIntegrationテストでのみテストできます。
- String-based HQL queries
- composite identifiers
- dirty checking methods
- any direct interaction with Hibernate
- 文字列ベースのHQLクエリ
- 複合主キー
- dirtyチェックメソッド
- Hibernateの直接操作
DomainClassUnitTestMixin
including:
上記以外の、よく使用されるGORM APIの大部分はDomainClassUnitTestMixin
を使用することでモック化することができます。
- Simple persistence methods like
save()
,delete()
etc. - Dynamic Finders
- Named Queries
- Query-by-example
- GORM Events
save()
やdelete()
といった永続化メソッド- ダイナミックファインダー
- 名前付きクエリ
- Exampleによるクエリ
- GORMのイベント
GrailsUnitTestMixin
's mockFor
method can come in handy to mock the missing pieces. Alternatively you can write an integration test which bootstraps the complete Grails environment at a cost of test execution time.
もしサポートされてない部分があった場合でも、GrailsUnitTestMixin
のmockFor
メソッドを使用することで足りない部分をモック化することができます。または、テストの実行時間はかかりますが、完全にGrails環境が立ち上がるIntegrationテストを使用することもできます。
The Basics
基本
DomainClassUnitTestMixin
is typically used in combination with testing either a controller, service or tag library where the domain is a mock collaborator defined by the Mock
annotation:
DomainClassUnitTestMixin
は、通常コントローラやサービス、またはタグライブラリといった、Mock
アノテーションでドメインがモックとして協調動作する必要がある場所で使用されます。
import grails.test.mixin.*@TestFor(SimpleController) @Mock(Simple) class SimpleControllerTests {
}
SimpleController
class and mocks the behavior of the Simple
domain class as well. For example consider a typical scaffolded save
controller action:
上記の例ではSimpleController
のテストでSimple
ドメインクラスとして振る舞うモックを宣言しています。例えば典型的なスキャフォルドで生成されたコントローラのsave
アクションについて考えてみます。
class BookController { def save() { def book = new Book(params) if (book.save(flush: true)) { flash.message = message( code: 'default.created.message', args: [message(code: 'book.label', default: 'Book'), book.id])}" redirect(action: "show", id: book.id) } else { render(view: "create", model: [bookInstance: book]) } } }
このアクションに対するテストは次のように書けます。
import grails.test.mixin.*@TestFor(BookController) @Mock(Book) class BookControllerTests {
void testSaveInvalidBook() { controller.save()
assert model.bookInstance != null assert view == '/book/create' }
void testSaveValidBook() { params.title = "The Stand" params.pages = "500"
controller.save()
assert response.redirectedUrl == '/book/show/1' assert flash.message != null assert Book.count() == 1 } }
Mock
annotation also supports a list of mock collaborators if you have more than one domain to mock:
複数のドメインのモックが必要な場合はMock
アノテーションにリストで指定することができます。
@TestFor(BookController) @Mock([Book, Author]) class BookControllerTests { … }
DomainClassUnitTestMixin
directly with the TestMixin
annotation:
別の方法としてTestMixin
アノテーションに直接DomainClassUnitTestMixin
を指定する方法もあります。
import grails.test.mixin.domain.DomainClassUnitTestMixin@TestFor(BookController) @TestMixin(DomainClassUnitTestMixin) class BookControllerTests { … }
mockDomain
method to mock domains during your test:
そしてテストの中でドメインをモック化するmockDomain
メソッドを呼び出します。
void testSave() { mockDomain(Author) mockDomain(Book) }
mockDomain
method also includes an additional parameter that lets you pass a Map of Maps to configure a domain, which is useful for fixture-like data:
mockDomain
メソッドは、ドメインを構築するマップの一覧を与えることで、データのフィクスチャを生成するような使い方もできます。
void testSave() { mockDomain(Book, [ [title: "The Stand", pages: 1000], [title: "The Shining", pages: 400], [title: "Along Came a Spider", pages: 300] ]) }
Testing Constraints
制約のテスト
There are 4 types of validateable classes:
- Domain Classes
- Classes Marked With The @Validateable Annotation
- Command Objects Which Have Been Made Valdiateable Automatically
- Classes Configured To Be Validateable via The
grails.validateable.classes
Config.groovy Property
The first 3 are easily testable in a unit test with no special configuration necessary as long as the test method is marked with @TestFor or explicitly applies the GrailsUnitTestMixin
using @TestMixin. See the examples below.
// src/groovy/com/demo/MyValidateable.groovy package com.demo@grails.validation.Validateable class MyValidateable { String name Integer age
static constraints = { name matches: /[A-Z].*/ age range: 1..99 } }
// grails-app/domain/com/demo/Person.groovy package com.democlass Person { String name
static constraints = { name matches: /[A-Z].*/ } }
// grails-app/controllers/com/demo/DemoController.groovy package com.democlass DemoController {
def addItems(MyCommandObject co) { if(co.hasErrors()) { render 'something went wrong' } else { render 'items have been added' } } }
class MyCommandObject { Integer numberOfItems
static constraints = { numberOfItems range: 1..10 } }
// test/unit/com/demo/PersonSpec.groovy package com.demoimport grails.test.mixin.TestFor import spock.lang.Specification
@TestFor(Person) class PersonSpec extends Specification {
void "Test that name must begin with an upper case letter"() { when: 'the name begins with a lower letter' def p = new Person(name: 'jeff')
then: 'validation should fail' !p.validate()
when: 'the name begins with an upper case letter' p = new Person(name: 'Jeff')
then: 'validation should pass' p.validate() } }
// test/unit/com/demo/DemoControllerSpec.groovy package com.demoimport grails.test.mixin.TestFor import spock.lang.Specification
@TestFor(DemoController) class DemoControllerSpec extends Specification {
void 'Test an invalid number of items'() { when: params.numberOfItems = 42 controller.addItems()
then: response.text == 'something went wrong' }
void 'Test a valid number of items'() { when: params.numberOfItems = 8 controller.addItems()
then: response.text == 'items have been added' } }
// test/unit/com/demo/MyValidateableSpec.groovy package com.demoimport grails.test.mixin.TestMixin import grails.test.mixin.support.GrailsUnitTestMixin import spock.lang.Specification
@TestMixin(GrailsUnitTestMixin) class MyValidateableSpec extends Specification {
void 'Test validate can be invoked in a unit test with no special configuration'() { when: 'an object is valid' def validateable = new MyValidateable(name: 'Kirk', age: 47)
then: 'validate() returns true and there are no errors' validateable.validate() !validateable.hasErrors() validateable.errors.errorCount == 0
when: 'an object is invalid' validateable.name = 'kirk'
then: 'validate() returns false and the appropriate error is created' !validateable.validate() validateable.hasErrors() validateable.errors.errorCount == 1 validateable.errors['name'].code == 'matches.invalid'
when: 'the clearErrors() is called' validateable.clearErrors()
then: 'the errors are gone' !validateable.hasErrors() validateable.errors.errorCount == 0
when: 'the object is put back in a valid state' validateable.name = 'Kirk'
then: 'validate() returns true and there are no errors' validateable.validate() !validateable.hasErrors() validateable.errors.errorCount == 0 } }
// test/unit/com/demo/MyCommandObjectSpec.groovy package com.demoimport grails.test.mixin.TestMixin import grails.test.mixin.support.GrailsUnitTestMixin import spock.lang.Specification
@TestMixin(GrailsUnitTestMixin) class MyCommandObjectSpec extends Specification {
void 'Test that numberOfItems must be between 1 and 10'() { when: 'numberOfItems is less than 1' def co = new MyCommandObject() co.numberOfItems = 0
then: 'validation fails' !co.validate() co.hasErrors() co.errors['numberOfItems'].code == 'range.toosmall'
when: 'numberOfItems is greater than 10' co.numberOfItems = 11
then: 'validation fails' !co.validate() co.hasErrors() co.errors['numberOfItems'].code == 'range.toobig'
when: 'numberOfItems is greater than 1' co.numberOfItems = 1
then: 'validation succeeds' co.validate() !co.hasErrors()
when: 'numberOfItems is greater than 10' co.numberOfItems = 10
then: 'validation succeeds' co.validate() !co.hasErrors() } }
For validateable classes which are not one of the first 3 types listed above but are configured with the grails.validateable.classes
property in Config.groovy
, one additional step is required to test validation. GrailsUnitTestMixin
provides a method named mockForConstraintsTests
that will mock validation support for these classes. See the example below.
// src/groovy/com/demo/Book.groovy package com.democlass Book { String title String author
static constraints = { author minSize: 5 } }
// grails-app/conf/Config.groovy grails.validateable.classes = [com.demo.Book]// ...
// test/unit/com/demo/BookSpec.groovy package com.demoimport grails.test.mixin.TestMixin import grails.test.mixin.support.GrailsUnitTestMixin import spock.lang.Specification
@TestMixin(GrailsUnitTestMixin) class BookSpec extends Specification {
void 'Test validation'() { given: mockForConstraintsTests Book
when: 'the author name has only 4 characters' def book = new Book() book.author = 'Jeff'
then: 'validation should fail' !book.validate() book.hasErrors() book.errors['author'] == 'minSize'
when: 'the author name has 5 characters' book.author = 'Jacob'
then: 'validation should pass' book.validate() !book.hasErrors() } }
Note that the mockForConstraintsTests
method changes the behavior of the errors object such that something like book.errors'author'
will evaluate to the name of the failed constraint, not a org.springframework.validation.FieldError
object. This is convenient for unit tests. If your unit test really does want a reference to the org.springframework.validation.FieldError
object use something like book.errors.getFieldError('author')
.
That's it for testing constraints. One final thing we would like to say is that testing the constraints in this way catches a common error: typos in the "constraints" property name which is a mistake that is easy to make and equally easy to overlook. A unit test for your constraints will highlight the problem straight away.
12.1.4 フィルタのユニットテスト
class CancellingFilters { def filters = { all(controller:"simple", action:"list") { before = { redirect(controller:"book") return false } } } }
list
action of the simple
controller and redirects to the book
controller. To test this filter you start off with a test that targets the SimpleController
class and add the CancellingFilters
as a mock collaborator:simple
コントローラのlist
アクションをインターセプトし、book
コントローラにリダイレクトします。このフィルタをテストするには、まずSimpleController
クラスを対象としたテストを作り、CancellingFilters
をモックコラボレータとして設定します:@TestFor(SimpleController) @Mock(CancellingFilters) class SimpleControllerTests {}
withFilters
method to wrap the call to an action in filter execution:withFilters
メソッドで囲むようにテストを実装します:void testInvocationOfListActionIsFiltered() {
withFilters(action:"list") {
controller.list()
}
assert response.redirectedUrl == '/book'
}
action
parameter is required because it is unknown what the action to invoke is until the action is actually called. The controller
parameter is optional and taken from the controller under test. If it is another controller you are testing then you can specify it:action
パラメータが必須であることに注意してください。
controller
パラメータは省略可能です。省略時はテスト対象のコントローラが適用されます。
もしテストしているのが別のコントローラである場合はそれを指定します。withFilters(controller:"book",action:"list") { controller.list() }
12.1.5 URLマッピングのユニットテスト
The Basics
基本
TestFor
annotation testing a particular URL mappings class. For example to test the default URL mappings you can do the following:
URLマッピングをテストするには、TestFor
アノテーションを使用します。例えば、デフォルトのURLマッピングをテストするためには次のように使用します。
import org.example.AuthorController import org.example.SimpleController@TestFor(UrlMappings) @Mock([AuthorController, SimpleController]) class UrlMappingsTests { … }
@Mock
annotation.
上記のように、テストを実施するURLマッピングの対象となるコントローラにはMock
アノテーションを追加しなければなりません。
Note that since the default UrlMappings
class is in the default package your test must also be in the default package
UrlMappings
クラスがデフォルトパッケージの中にあるので、あなたが実行するテストもデフォルトパッケージの中になければいけません。
grails.test.mixin.web.UrlMappingsUnitTestMixin
for testing URL mappings. These include:
URLマッピングをテストするためにgrails.test.mixin.web.UrlMappingsUnitTestMixin
には以下のような便利なメソッドが定義されています。
assertForwardUrlMapping
- Asserts a URL mapping is forwarded for the given controller class (note that controller will need to be defined as a mock collaborate for this to work)
assertForwardUrlMapping
- 指定したコントローラクラスにフォワードするURLマッピングを検証する(コントローラはモックコラボレータとして定義される必要があることに注意してください)
assertReverseUrlMapping
- Asserts that the given URL is produced when reverse mapping a link to a given controller and action
assertReverseUrlMapping
- 指定したURLが、与えられたコントローラとアクションからリバースマッピングしたリンクとして生成されるか検証する
assertUrlMapping
- Asserts a URL mapping is valid for the given URL. This combines theassertForwardUrlMapping
andassertReverseUrlMapping
assertions
assertUrlMapping
- 指定したURLに対応するURLマッピングの妥当性を検証する。これは、assertForwardUrlMapping
とassertReverseUrlMapping
を組み合わせたものです。
Asserting Forward URL Mappings
URLマッピングの転送の検証
assertForwardUrlMapping
to assert that a given URL maps to a given controller. For example, consider the following URL mappings:
指定したURLが、期待したコントローラにマップされるか検証するためにassertForwardUrlMapping
が使用できます。例えば、以下のようなURLマッピングについて考えてみます。
static mappings = { "/action1"(controller: "simple", action: "action1") "/action2"(controller: "simple", action: "action2") }
このようなURLマッピングのテストは次のように書けます。
void testUrlMappings() {assertForwardUrlMapping("/action1", controller: 'simple', action: "action1")
assertForwardUrlMapping("/action2", controller: 'simple', action: "action2")
shouldFail { assertForwardUrlMapping("/action2", controller: 'simple', action: "action1") } }
Assert Reverse URL Mappings
URLマッピングのリバース検証
assertReverseUrlMapping
to check that correct links are produced for your URL mapping when using the link
tag in GSP views. An example test is largely identical to the previous listing except you use assertReverseUrlMapping
instead of assertForwardUrlMapping
. Note that you can combine these 2 assertions with assertUrlMapping
.
GSPのビューでlink
タグを使用した場合に、URLマッピングから生成されるリンクを確認(チェック)するためにassertReverseUrlMapping
を使用できます。
assertReverseUrlMapping
の代わりにassertForwardUrlMapping
を使用する以外は上記の例とほとんど同じです。
assertUrlMapping
はこれら2つのアサーションを組み合わせた検証が出来ます。
Simulating Controller Mapping
コントローラのマッピングをシミュレート
UrlMappings
as a mock collaborator and the mapURI
method. For example:
URLマッピングの妥当性をチェックするためのアサーションに加えて、UrlMappings
をモックとして指定しmapURI
メソッドを使用することで、コントローラへのマッピングをシミュレートすることができます。
@TestFor(SimpleController) @Mock(UrlMappings) class SimpleControllerTests {void testControllerMapping() {
SimpleController controller = mapURI('/simple/list') assert controller != null
def model = controller.list() assert model != null } }
12.1.6 コラボレータのモック化
mockFor()
method that is available when using the TestFor
annotation. The signature of mockFor
is:
mockFor()
メソッドがあります。これはTestFor
アノテーションを使用している場合にも使用できます。mockFor
は以下のように使用します。mockFor(class, loose = false)
mockFor
を使用したモックでは、demand(要求)がstrict(厳密)、またはloose(緩やか)のどちらであるかを指定する必要があります。def strictControl = mockFor(MyService) strictControl.demand.someMethod(0..2) { String arg1, int arg2 -> … } strictControl.demand.static.aStaticMethod {-> … }
mockControl.createMock()
to get an actual mock instance of the class that you are mocking. You can call this multiple times to create as many mock instances as you need. And once you have executed the test method, call mockControl.verify()
to check that the expected methods were called.
mockControl.createMock()
メソッドを呼ぶことで、モックインスタンスを作成します。複数のモックインスタンスが必要な場合は、必要なだけこのメソッドを呼び出すことで、複数のモックインスタンスが作成できます。また期待するメソッドの呼び出しを検証するにはmockControl.verify()
を呼び出してください。demandExplicit
method that can be used in place of demand. This will check the mocked class's metaClass and throw an ExplicitDemandException if a method with that name and signature doesn't exist. For example, given the service:
demandExplicit
メソッドも提供しています。これはモックするクラスのmetaClassをチェックし、もしそのメソッドの名前、シグネチャが存在しない場合に、ExplicitDemandExceptionをスローします。例えば次のようなサービスがあるとします。class MyService {
def someMethod(String s) { … }
}
def strictControl = mockFor(MyService)
//Works just like the demand method since method signature exists on the class
strictControl.demandExplicit.someMethod(1) { String arg1 }
def strictControl = mockFor(MyService) //Throws ExplicitDemandException because method signature doesn't exist strictControl.demandExplicit.someMethod(1) { String arg1, String arg2 }
def looseControl = mockFor(MyService, true)
12.1.7 コーデックのモック化
GrailsUnitTestMixin
provides a mockCodec
method for mocking custom codecs which may be invoked while a unit test is running.
GrailsUnitTestMixin
はカスタムコーデックのモックを生成するためのmockCodec
メソッドを提供しています。このメソッドはユニットテストの実施中に呼び出される可能性があります。
mockCodec(MyCustomCodec)
コーデックのモック生成に失敗している場合は、ユニットテストがMissingMethodException
で終了する可能性があります。
12.2 インテグレーションテスト
class MyServiceTests extends GroovyTestCase { void testSomething() { log.info "Starting tests" … } }
log
property in the example above is an instance of java.util.logging.Logger
(inherited from the base class, not injected by Grails), which doesn't have the same methods as the log
property injected into your application artifacts. For example, it doesn't have debug()
or trace()
methods, and the equivalent of warn()
is in fact warning()
.log
のプロパティにはjava.util.logging.Logger
のインスタンスが設定され(Grailsによって注入されるのではなく、ベースクラスから継承される)、アプリケーション側で注入されるlog
プロパティと同じメソッドは持っていません。例えば、debug()
やtrace()
メソッドがなく、warn()
(と同じ意味を持つもの)がwarning()
になります。トランザクション
transactional
property to your test class to check transactional behaviour:transactional
プロパティをテストクラスに追加することで、トランザクション制御を抑止することができます:class MyServiceTests extends GroovyTestCase { static transactional = falsevoid testMyTransactionalServiceMethod() { … } }
tearDown
method, so these tests don't interfere with standard transactional tests that expect a clean database.tearDown
メソッドなどで、永続化されたすべてのデータを削除するようにしてください。コントローラのテスト
class FooController {def text() { render "bar" }
def someRedirect() { redirect(action:"bar") } }
class FooControllerTests extends GroovyTestCase {void testText() { def fc = new FooController() fc.text() assertEquals "bar", fc.response.contentAsString }
void testSomeRedirect() { def fc = new FooController() fc.someRedirect() assertEquals "/foo/bar", fc.response.redirectedUrl } }
response
is an instance of MockHttpServletResponse
which we can use to obtain the generated content with contentAsString
(when writing to the response) or the redirected URL. These mocked versions of the Servlet API are completely mutable (unlike the real versions) and hence you can set properties on the request such as the contextPath
and so on.response
はMockHttpServletResponse
のインスタンスです。このインスタンスでは、レスポンスを書き出すときであればcontentAsString
により生成されたコンテンツが取得でき、リダイレクトの場合はリダイレクトされたURLが取得できます。これらのServlet APIのモックバージョンは(実際のAPIとは異なり)何でも変更可能で、contextPath
などリクエストのプロパティについても設定可能です。サービスを伴うコントローラのテスト
class FilmStarsController { def popularityServicedef update() { // do something with popularityService } }
class FilmStarsTests extends GroovyTestCase { def popularityServicevoid testInjectedServiceInController () { def fsc = new FilmStarsController() fsc.popularityService = popularityService fsc.update() } }
コマンドオブジェクトを使っているコントローラのテスト
class AuthenticationController { def signup(SignupForm form) { … } }
def controller = new AuthenticationController() controller.params.login = "marcpalmer" controller.params.password = "secret" controller.params.passwordConfirm = "secret" controller.signup()
signup()
as a call to the action and populates the command object from the mocked request parameters. During controller testing, the params
are mutable with a mocked request supplied by Grails.signup()
を呼び出しているのを見て、モック化されたリクエストパラメータからなんと自動的にコマンドオブジェクトに値を渡してくれます。ちなみに、コントローラのテストにおいて、Grailsが用意したモック化されたリクエストのparams
は変更可能です。コントローラとレンダーメソッドのテスト
def save() { def book = Book(params) if (book.save()) { // handle } else { render(view:"create", model:[book:book]) } }
modelAndView
property of the controller. The modelAndView
property is an instance of Spring MVC's ModelAndView class and you can use it to the test the result of an action:modelAndView
プロパティの中には保存されています。modelAndView
プロパティはSpring MVCのModelAndViewクラスで、アクションの結果をテストするのに利用できます:def bookController = new BookController()
bookController.save()
def model = bookController.modelAndView.model.book
リクエストデータをシミュレートする
def create() {
[book: new Book(params.book)]
}
void testCreateWithXML() {def controller = new BookController()
controller.request.contentType = 'text/xml' controller.request.content = '''\ <?xml version="1.0" encoding="ISO-8859-1"?> <book> <title>The Stand</title> … </book> '''.stripIndent().getBytes() // note we need the bytes
def model = controller.create() assert model.book assertEquals "The Stand", model.book.title }
void testCreateWithJSON() {def controller = new BookController()
controller.request.contentType = "application/json" controller.request.content = '{"id":1,"class":"Book","title":"The Stand"}'.getBytes()
def model = controller.create() assert model.book assertEquals "The Stand", model.book.title }
With JSON don't forget theclass
property to specify the name the target type to bind to. In XML this is implicit within the name of the<book>
node, but this property is required as part of the JSON packet.
JSONを用いる場合、class
プロパティにて結びつけるターゲットの型の名前を指定することを忘れてはいけません。XMLでは暗黙的に<book>
ノードの名前が使われますが、JSONではこのプロパティがJSONパケットの一部として必要になります。
Webフローのテスト
grails.test.WebFlowTestCase
which subclasses Spring Web Flow's AbstractFlowExecutionTests class.grails.test.WebFlowTestCase
と呼ばれる特別なテストハーネスが必要になります。
Subclasses of WebFlowTestCase
must be integration tests
WebFlowTestCase
のサブクラスは、必ずインテグレーションテストでなければなりません。
class ExampleController {def exampleFlow() { start { on("go") { flow.hello = "world" }.to "next" } next { on("back").to "start" on("go").to "subber" } subber { subflow(action: "sub") on("end").to("end") } end() }
def subFlow() { subSubflowState { subflow(controller: "other", action: "otherSub") on("next").to("next") } … } }
getFlow
method:getFlow
をオーバライドすることにより、"フロー定義"を使っていることをテストハーネスに知らせる必要があります:import grails.test.WebFlowTestCaseclass ExampleFlowTests extends WebFlowTestCase { def getFlow() { new ExampleController().exampleFlow } … }
getFlowId
method, otherwise the default is test
:getFlowId
メソッドをオーバライドして、フローIDを指定することができます。指定しないならデフォルトとしてtest
が使われます:
import grails.test.WebFlowTestCaseclass ExampleFlowTests extends WebFlowTestCase { String getFlowId() { "example" } … }
protected void setUp() { super.setUp()registerFlow("other/otherSub") { // register a simplified mock start { on("next").to("end") } end() }
// register the original subflow registerFlow("example/sub", new ExampleController().subFlow) }
startFlow
method:startFlow
メソッドによりフローを開始します:void testExampleFlow() { def viewSelection = startFlow() … }
signalEvent
method to trigger an event:signalEvent
を使います:void testExampleFlow() { … signalEvent("go") assert "next" == flowExecution.activeSession.state.id assert "world" == flowScope.hello }
hello
variable into the flow scope.hello
変数をフローのスコープに設定します。タグライブラリのテスト
StreamCharBuffer
but this class implements all of the methods of String
). So for example if you have a tag library like this:String
の全てのメソッドを実装したStreamCharBuffer
となります)が返されるので単純です。例えば、タグライブラリのテストはこのようになります:class FooTagLib {def bar = { attrs, body -> out << "<p>Hello World!</p>" }
def bodyTag = { attrs, body -> out << "<${attrs.name}>" out << body() out << "</${attrs.name}>" } }
class FooTagLibTests extends GroovyTestCase {void testBarTag() { assertEquals "<p>Hello World!</p>", new FooTagLib().bar(null, null).toString() }
void testBodyTag() { assertEquals "<p>Hello World!</p>", new FooTagLib().bodyTag(name: "p") { "Hello World!" }.toString() } }
testBodyTag
, we pass a block that returns the body of the tag. This is convenient to representing the body as a String.testBodyTag
の例を見てください。この例ではタグのボディを返すブロックを渡しています。これはタグ本体を文字列として表現するのに便利です。GroovyPagesTestCaseを用いたタグライブラリのテスト
grails.test.GroovyPagesTestCase
class to test tag libraries with integration tests.grails.test.GroovyPagesTestCase
クラスを用いたタグライブラリのテストが可能です。GroovyPagesTestCase
class is a subclass of the standard GroovyTestCase
class and adds utility methods for testing the output of GSP rendering.GroovyPagesTestCase
クラスは標準的なGroovyTestCase
クラスのサブクラスであり、GSPレンダリングの出力をテストするためのユーティリティメソッドが追加されています。
GroovyPagesTestCase
can only be used in an integration test.
GroovyPagesTestCase
はインテグレーションテストの中だけで使えます。
import java.text.SimpleDateFormatclass FormatTagLib { def dateFormat = { attrs, body -> out << new SimpleDateFormat(attrs.format) << attrs.date } }
class FormatTagLibTests extends GroovyPagesTestCase { void testDateFormat() { def template = '<g:dateFormat format="dd-MM-yyyy" date="${myDate}" />'def testDate = … // create the date assertOutputEquals('01-01-2008', template, [myDate:testDate]) } }
applyTemplate
method of the GroovyPagesTestCase
class:GroovyPagesTestCase
クラスのapplyTemplate
メソッドを使ったGSPの結果も得ることもできます:class FormatTagLibTests extends GroovyPagesTestCase { void testDateFormat() { def template = '<g:dateFormat format="dd-MM-yyyy" date="${myDate}" />'def testDate = … // create the date def result = applyTemplate(template, [myDate:testDate])
assertEquals '01-01-2008', result } }
ドメインクラスのテスト
void testQuery() { def books = [ new Book(title: "The Stand"), new Book(title: "The Shining")] books*.save()assertEquals 2, Book.list().size() }
Book
instances when called. Calling save
only indicates to Hibernate that at some point in the future these instances should be persisted. To commit changes immediately you "flush" them:Book
インスタンスが呼び出されたときには実際には保存されていないので失敗するでしょう。save
を呼び出しても単にHibernateに未来のある時点でインスタンスが保存されるべきであることを示唆するだけです。ただちに変更をコミットするためには"フラッシュ"をします:void testQuery() { def books = [ new Book(title: "The Stand"), new Book(title: "The Shining")] books*.save(flush: true)assertEquals 2, Book.list().size() }
flush
with a value of true
the updates will be persisted immediately and hence will be available to the query later on.flush
にtrue
を渡しているので、データの更新はただちに保存され、後のクエリでも利用可能になります。
12.3 ファンクショナルテスト
Functional tests involve making HTTP requests against the running application and verifying the resultant behaviour. The functional testing phase differs from the integration phase in that the Grails application is now listening and responding to actual HTTP requests. This is useful for end-to-end testing scenarios, such as making REST calls against a JSON API.Canoo Webtest
- http://grails.org/plugin/webtestG-Func
- http://grails.org/plugin/functional-testGeb
- http://grails.org/plugin/gebSelenium-RC
- http://grails.org/plugin/selenium-rcWebDriver
- http://grails.org/plugin/webdriver
共通オプション
inlineオプション
-inline
option specifies that the grails application should be started inline (i.e. like run-app
).-inline
オプションが指定されるとGrailsアプリケーションがインライン起動されます(例えばrun-app
のような)。baseUrl
or war
options are set-inline
オプションは-baseUrl
か-war
のどちらかが設定されていないと、暗黙的に有効になりますwarオプション
-war
option specifies that the grails application should be packaged as a war and started. This is useful as it tests your application in a production-like state, but it has a longer startup time than the -inline
option. It also runs the war in a forked JVM, meaning that you cannot access any internal application objects.-war
オプションを指定すると、Grailsアプリケーションはwarファイルにパッケージ化した後に起動されます。このオプションはアプリケーションを実際にプロダクトと同じ状態でテストすることができるので便利です。しかし、-inline
オプションよりも起動に時間がかかります。また、warで起動するとフォークされたJVM上で実行されます。これは内部のオブジェクトにアクセスできないことを意味しています。grails test-app functional: -war
httpsオプション
-https
option results in the application being able to receive https requests as well as http requests. It is compatible with both the -inline
and -war
options.-https
オプションはhttpリクエストと同様にアプリケーションがhttpsリクエストを受け付けられるようにします。このオプションは-inline
と-war
の両方のオプションと一緒に使うことができます。grails test-app functional: -https
-httpsBaseUrl
option is also given.-https
オプションを使っていてもテストで使われる base url はhttpsにはなりません。-httpsBaseUrl
をあわせて指定しない限り、httpのままとなります。httpsBaseUrlオプション
-httpsBaseUrl
causes the implicit base url to be used for tests to be a https url.-httpsBaseUrl
オプションを使えば暗黙的に設定されている base url がテスト時にhttpsのURLとして使われます。grails test-app functional: -httpsBaseUrl
-baseUrl
option is specified.-httpsBaseUrl
オプションは-baseUrl
オプションが指定されると無視されます。baseUrlオプション
baseUrl
option allows the base url for tests to be specified.-baseUrl
オプションによりテスト実施時の base url を指定することができます。grails test-app functional: -baseUrl=http://mycompany.com/grailsapp
-inline
or -war
are given as well. To use a custom base url but still test against the local Grails application you must specify one of either the -inline
or -war
options.-baseUrl
オプションが指定されていると、ローカル環境でのGrailsアプリケーションを-inline
や-war
を指定しないで起動することができなくなります。ローカル環境でのGrailsアプリケーションで base url を指定するには、必ず-inline
か-war
のどちらかのオプションを指定する必要があります。
13 国際化
A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country, region, or culture.Locale オブジェクトは、特定の地理的、国家的、または文化的地域を表すためのものです。ある操作で Locale を必要とするタスクがある場合、その操作をロケールに依存する操作といいます。この場合、情報は Locale によりユーザに合わせて調整されます。たとえば、数値を表示するのは、ロケールに依存する操作です。この数値は、ユーザの国や地域、文化の習慣や規則に従ってフォーマットする必要があります。
13.1 メッセージバンドルを理解する
grails-app/i18n
directory and are simple Java properties files.grails-app/i18n
ディレクトリに配置します。messages
by convention and ends with the locale. Grails ships with several message bundles for a whole range of languages within the grails-app/i18n
directory. For example:messages
からはじまり、ロケール名称で終わります。Grailsでは幾つかの言語のメッセージバンドルをgrails-app/i18n
ディレクトリに同梱しています。例として:
- messages.properties
- messages_da.properties
- messages_de.properties
- messages_es.properties
- messages_fr.properties
- ...
messages.properties
for messages unless the user has specified a locale. You can create your own message bundle by simply creating a new properties file that ends with the locale you are interested. For example messages_en_GB.properties
for British English.messages.properties
を参照します。
独自のメッセージバンドルを作成するには、末尾がロケールのプロパティファイルを新規に作成します。たとえば、messages_ja_JP.properties
とすれば日本国+日本語になります。
13.2 ロケールの変更
Accept-Language
header. However, you can provide users the capability to switch locales by simply passing a parameter called lang
to Grails as a request parameter:Accept-Languag
ヘッダーによりロケールが決まります。リクエストパラメータにlang
を指定することでロケールを変更できます。/book/list?lang=es
13.3 メッセージ読込
ビュー内でのメッセージ読み込み Reading Messages in the View
<g:message code="my.localized.content" />
messages.properties
(with appropriate locale suffix) such as the one below then Grails will look up the message:messages.properties
(妥当なロケール接尾辞が付いている)に有る場合、Grailsがメッセージを取得できます:my.localized.content=Hola, Me llamo John. Hoy es domingo.
<g:message code="my.localized.content" args="${ ['Juan', 'lunes'] }" />
my.localized.content=Hola, Me llamo {0}. Hoy es {1}.
コントローラとタグライブラリ内でのメッセージ読み込み Reading Messages in Controllers and Tag Libraries
def show() {
def msg = message(code: "my.localized.content", args: ['Juan', 'lunes'])
}
g.
:g.
を使用します:def myTag = { attrs, body ->
def msg = g.message(code: "my.localized.content", args: ['Juan', 'lunes'])
}
13.4 スカッフォルドとi18n
flash
messages use i18n to resolve locale-specific messages.flash
メッセージを使用して国際化にロケール対応メッセージを使用しています。
14 セキュリティ
Grailsが自動的に行うこと
- All standard database access via GORM domain objects is automatically SQL escaped to prevent SQL injection attacks
- The default scaffolding templates HTML escape all data fields when displayed
- Grails link creating tags (link, form, createLink, createLinkTo and others) all use appropriate escaping mechanisms to prevent code injection
- Grails provides codecs to let you trivially escape data when rendered as HTML, JavaScript and URLs to prevent injection attacks here.
- GORM経由でのすべての標準的なデータベースアクセスにおける、SQLインジェクション攻撃を防ぐための自動的なエスケープ処理
- デフォルトのスカッフォルドテンプレートのHTMLにおける、すべてのデータフィールドに対する表示時のエスケープ処理
- Grailsのリンク作成タグ(link、form、createLink、createLinkTo他)における、コードインジェクションを防ぐための適切なエスケープ機構
- GrailsでHTML、JavaScript、URLをレンダリングする際の、データを手軽にエスケープ処理しインジェクション攻撃を防ぐコーデックの提供
14.1 攻撃からの防御
SQLインジェクション
def vulnerable() { def books = Book.find("from Book as b where b.title ='" + params.title + "'") }
def vulnerable() {
def books = Book.find("from Book as b where b.title ='${params.title}'")
}
def safe() {
def books = Book.find("from Book as b where b.title = ?",
[params.title])
}
def safe() {
def books = Book.find("from Book as b where b.title = :title",
[title: params.title])
}
フィッシング
XSS - クロスサイトスクリプティングインジェクション
successURL
parameter for example to determine where to redirect a user to after a successful login, attackers can imitate your login procedure using your own site, and then redirect the user back to their own site once logged in, potentially allowing JavaScript code to then exploit the logged-in account on the site.successURL
パラメータを使うような場合、攻撃者は、あなた自身のサイトを利用してログイン手順を偽装し、ユーザがログインしようとしたときに攻撃者自身のサイトにリダイレクトさせることができてしまいます。これは、潜在的に、サイト上のログインアカウントを悪用するJavaScriptコードを許していることになります。クロスサイトリクエストフォージェリ
useToken
attribute on your forms. See Handling Duplicate Form Submissions for more information on how to use it. An additional measure would be to not use remember-me cookies.useToken
属性を使うことです。使い方についての詳細は、フォーム二重送信のハンドリングを参照してください。加えて、「次回からパスワードの入力を省略する」というような機能を提供するクッキーを使わないことも対策の一つです。HTML/URLインジェクション
サービス妨害
def safeMax = Math.max(params.max?.toInteger(), 100) // limit to 100 results return Book.list(max:safeMax)
def safeMax = Math.max(params.max?.toInteger(), 100) // 結果を100件に制限する return Book.list(max:safeMax)
推測可能なID
14.2 クロスサイトスクリプティング(XSS)防御
Cross Site Scripting (XSS) attacks are a common attack vector for web applications. They typically involve submitting HTML or Javascript code in a form such that when that code is displayed, the browser does something nasty. It could be as simple as popping up an alert box, or it could be much worse. The solution is to escape all untrusted user input when it is displayed in a page. For example,<script>alert('Got ya!');</script>
will become
<script>alert('Got ya!');</script>
when rendered, nullifying the effects of the malicious input.
By default, Grails plays it safe and escapes all content in ${}
expressions in GSPs. All the standard GSP tags are also safe by default, escaping any relevant attribute values.
So what happens when you want to stop Grails from escaping some content? There are valid use cases for putting HTML into the database and rendering it as-is, as long as that content is trusted. In such cases, you can tell Grails that the content is safe as should be rendered raw, i.e. without any escaping:
<section>${raw(page.content)}</section>
The raw()
method you see here is available from controllers, tag libraries and GSP pages.
Although Grails plays it safe by default, that is no guarantee that your application will be invulnerable to an XSS-style attack. Such an attack is less likely to succeed than would otherwise be the case, but developers should always be conscious of potential attack vectors and attempt to uncover vulnerabilities in the application during testing. It's also easy to switch to an unsafe default, thereby increasing the risk of a vulnerability being introduced.
It's difficult to make a solution that works for everyone, and so Grails provides a lot of flexibility with regard to fine-tuning how escaping works, allowing you to keep most of your application safe while switching off default escaping or changing the codec used for pages, tags, page fragments, and more.
Configuration
It is recommended that you review the configuration of a newly created Grails application to garner an understanding of XSS prevention works in Grails.
GSP features the ability to automatically HTML encode GSP expressions, and as of Grails 2.3 this is the default configuration. The default configuration (found in Config.groovy
) for a newly created Grails application can be seen below:
grails { views { gsp { encoding = 'UTF-8' htmlcodec = 'xml' // use xml escaping instead of HTML4 escaping codecs { expression = 'html' // escapes values inside ${} scriptlet = 'html' // escapes output from scriptlets in GSPs taglib = 'none' // escapes output from taglibs staticparts = 'none' // escapes output from static template parts } } // escapes all not-encoded output at final stage of outputting filteringCodecForContentType { //'text/html' = 'html' } } }
GSP features several codecs that it uses when writing the page to the response. The codecs are configured in the codecs
block and are described below:
expression
- The expression codec is used to encode any code found within ${..} expressions. The default for newly created application ishtml
encoding.scriptlet
- Used for output from GSP scriplets (<% %>, <%= %> blocks). The default for newly created applications ishtml
encodingtaglib
- Used to encode output from GSP tag libraries. The default isnone
for new applications, as typically it is the responsibility of the tag author to define the encoding of a given tag and by specifyingnone
Grails remains backwards compatible with older tag libraries.staticparts
- Used to encode the raw markup output by a GSP page. The default isnone
.
Double Encoding Prevention
Versions of Grails prior to 2.3, included the ability to set the default codec to html
, however enabling this setting sometimes proved problematic when using existing plugins due to encoding being applied twice (once by the html
codec and then again if the plugin manually called encodeAsHTML
).
Grails 2.3 includes double encoding prevention so that when an expression is evaluated, it will not encode if the data has already been encoded (Example ${foo.encodeAsHTML()}
).
Raw Output
If you are 100% sure that the value you wish to present on the page has not been received from user input, and you do not wish the value to be encoded then you can use the raw
method:
${raw(book.title)}
The 'raw' method is available in tag libraries, controllers and GSP pages.
Per Plugin Encoding
Grails also features the ability to control the codecs used on a per plugin basis. For example if you have a plugin named foo
installed, then placing the following configuration in your application's Config.groovy
will disable encoding for only the foo
plugin
foo.grails.views.gsp.codecs.expression = "none"
Per Page Encoding
You can also control the various codecs used to render a GSP page on a per page basis, using a page directive:
<%@page expressionCodec="none" %>
Per Tag Library Encoding
Each tag library created has the opportunity to specify a default codec used to encode output from the tag library using the "defaultEncodeAs" property:
static defaultEncodeAs = 'html'
Encoding can also be specified on a per tag basis using "encodeAsForTags":
static encodeAsForTags = [tagName: 'raw']
Context Sensitive Encoding Switching
Certain tags require certain encodings and Grails features the ability to enable a codec only a certain part of a tag's execution using the "withCodec" method. Consider for example the "<g:javascript>"" tag which allows you to embed JavaScript code in the page. This tag requires JavaScript encoding, not HTML coding for the execution of the body of the tag (but not for the markup that is output):
out.println '<script type="text/javascript">' withCodec("JavaScript") { out << body() } out.println() out.println '</script>'
Forced Encoding for Tags
If a tag specifies a default encoding that differs from your requirements you can force the encoding for any tag by passing the optional 'encodeAs' attribute:
<g:message code="foo.bar" encodeAs="JavaScript" />
Default Encoding for All Output
The default configuration for new applications is fine for most use cases, and backwards compatible with existing plugins and tag libraries. However, you can also make your application even more secure by configuring Grails to always encode all output at the end of a response. This is done using the filteringCodecForContentType
configuration in Config.groovy
:
grails.views.gsp.filteringCodecForContentType.'text/html' = 'html'
Note that, if activated, the staticparts
codec typically needs to be set to raw
so that static markup is not encoded:
codecs {
expression = 'html' // escapes values inside ${}
scriptlet = 'html' // escapes output from scriptlets in GSPs
taglib = 'none' // escapes output from taglibs
staticparts = 'raw' // escapes output from static template parts
}
14.3 エンコード・デコードオブジェクト
コーデッククラス
grails-app/utils/
directory.grails-app/utils/
ディレクトリ以下にあるコーデックを動的にロードします。grails-app/utils/
for class names that end with the convention Codec
. For example one of the standard codecs that ships with Grails is HTMLCodec
.grails-app/utils/
ディレクトリ以下にある、Codec
という名前で終わるクラスを探します。例えば、Grailsに標準で実装されているコーデックの一つにHTMLCodec
があります。encode
closure Grails will create a dynamic encode
method and add that method to the Object
class with a name representing the codec that defined the encode closure. For example, the HTMLCodec
class defines an encode
closure, so Grails attaches it with the name encodeAsHTML
.encode
クロージャが定義されている場合、Grailsは動的なencode
メソッドを作成し、そのクロージャを定義しているコーデックの名前でそのメソッドをObject
クラスに追加します。例えば、HTMLCodec
クラスではencode
クロージャが定義されているため、GrailsはencodeAsHTML
という名前でメソッドを追加します。HTMLCodec
and URLCodec
classes also define a decode
closure, so Grails attaches those with the names decodeHTML
and decodeURL
respectively. Dynamic codec methods may be invoked from anywhere in a Grails application. For example, consider a case where a report contains a property called 'description' which may contain special characters that must be escaped to be presented in an HTML document. One way to deal with that in a GSP is to encode the description property using the dynamic encode method as shown below:HTMLCodec
クラスとURLCodec
クラスではdecode
クロージャも定義されているので、GrailsはこれらをそれぞれdecodeHTML
, decodeURL
という名前で追加します。動的なコーデックメソッドはGrailsアプリケーションのどこからでも呼び出すことができます。例えば、report
がdescription
という名前のプロパティを持っているケースを想定します。description
は特殊文字を文字を含んでいる可能性があるため、HTMLドキュメントとして表示させる前にエスケープする必要があるとします。GSPでこれを実現する一つの方法は、以下のように、動的なエンコードメソッドを使用してdescription
プロパティをエンコードすることです:${report.description.encodeAsHTML()}
value.decodeHTML()
syntax.value.decodeHTML()
というような形で行うことができます。標準コーデック
<input name="comment.message" value="${comment.message.encodeAsHTML()}"/>
Note that the HTML encoding does not re-encode apostrophe/single quote so you must use double quotes on attribute values to avoid text with apostrophes affecting your page.HTMLエンコードでは、アポストロフィ/シングルクォートを再エンコードしないことに注意してください。エンコードする文字列にアポストロフィが入っている場合に備えて、属性の値はダブルクォートで括ってください。
<a href="/mycontroller/find?searchKey=${lastSearch.encodeAsURL()}">
Repeat last search
</a>
Your registration code is: ${user.registrationCode.encodeAsBase64()}
Element.update('${elementId}',
'${render(template: "/common/message").encodeAsJavaScript()}')
Selected colour: #${[255,127,255].encodeAsHex()}
Your API Key: ${user.uniqueID.encodeAsMD5()}
byte[] passwordHash = params.password.encodeAsMD5Bytes()
Your API Key: ${user.uniqueID.encodeAsSHA1()}
byte[] passwordHash = params.password.encodeAsSHA1Bytes()
Your API Key: ${user.uniqueID.encodeAsSHA256()}
byte[] passwordHash = params.password.encodeAsSHA256Bytes()
カスタムコーデック
grails-app/utils/
directory and the class name must end with Codec
. The codec may contain a static
encode
closure, a static
decode
closure or both. The closure must accept a single argument which will be the object that the dynamic method was invoked on. For Example:grails-app/utils/
ディレクトリ以下に配置され、かつ、クラス名はCodec
で終わる必要があります。コーデックにはstatic
encode
クロージャとstatic
decode
クロージャのいずれかまたは両方を定義することができます。これらのクロージャは、1引数 (動的なメソッドとして実行された際にエンコード/デコード対象のオブジェクトになります) を受け付ける必要があります。例えば、以下のように記述します:class PigLatinCodec { static encode = { str -> // convert the string to pig latin and return the result } }
${lastName.encodeAsPigLatin()}
14.4 認証
grails-app/conf/SecurityFilters.groovy
by running:grails-app/conf/SecurityFilters.groovy
というクラスに新しいフィルタセットが生成されます:grails create-filters security
class SecurityFilters { def filters = { loginCheck(controller: '*', action: '*') { before = { if (!session.user && actionName != "login") { redirect(controller: "user", action: "login") return false } } } } }
loginCheck
filter intercepts execution before all actions except login
are executed, and if there is no user in the session then redirect to the login
action.loginCheck
フィルタがすべてのアクションの実行前にインターセプトされます。ただし、セッションにユーザが存在しない状態でlogin
以外のアクションが呼び出された場合は、login
アクションにリダイレクトされます。login
action itself is simple too:login
アクションの実装も簡単です:def login() { if (request.get) { return // render the login view }def u = User.findByLogin(params.login) if (u) { if (u.password == params.password) { session.user = u redirect(action: "home") } else { render(view: "login", model: [message: "Password incorrect"]) } } else { render(view: "login", model: [message: "User not found"]) } }
14.5 セキュリティプラグイン
14.5.1 Spring Security
14.5.2 Shiro
JsecAuthBase
in each controller you want secured and then provide an accessControl
block to setup the roles. An example below:JsecAuthBase
という基底クラスを継承し、accessControl
ブロックを使用してロールを設定します。以下に例を示します:class ExampleController extends JsecAuthBase { static accessControl = { // All actions require the 'Observer' role. role(name: 'Observer')// The 'edit' action requires the 'Administrator' role. role(name: 'Administrator', action: 'edit')
// Alternatively, several actions can be specified. role(name: 'Administrator', only: [ 'create', 'edit', 'save', 'update' ]) } … }
15 プラグイン
15.1 プラグインの作成とインストール
Creating Plugins
プラグインの作成
Grailsプラグインの新規作成は、以下のコマンドを実行するだけであり、とても簡単です:
grails create-plugin [PLUGIN NAME]
grails create-plugin example
would create a new plugin project called example
.grails create-plugin example
を実行すると、example
という新規プラグインプロジェクトが作成されます。Make sure the plugin name does not contain more than one capital in a row, or it won't work. Camel case is fine, though.
The only plugins included in a new plugin project are Tomcat and Release. Hibernate is not included by default.新規プラグインプロジェクトには、TomcatプラグインとReleaseプラグインが含められています。Hibernateプラグインはデフォルトの状態では含められていません。
Grailsプラグインの構成が「通常のGrailsプロジェクト」と同じであることには利点が多くあります。例えば、以下を実行することでテストが実行できます。
grails run-app
Plugin projects don't provide an index.gsp by default since most plugins don't need it. So, if you try to view the plugin running in a browser right after creating it, you will receive a page not found error. You can easily create agrails-app/views/index.gsp
for your plugin if you'd like.プラグインプロジェクトは、index.gspをデフォルトでは提供しません。なぜならほとんどのプラグインでは必要ないからです。なので、プラグイン起動後にブラウザで確認しようとすると「ページが見つかりません」というエラーになるでしょう。もちろん、もしそうしたければプラグインプロジェクト中に
grails-app/views/index.gsp
を作成しても全く問題ありません。
GrailsPlugin
and is found in the root of the plugin project. For example:
GrailsPlugin
」であり、プラグインプロジェクトのルートディレクトリに配置されます。例えば:class ExampleGrailsPlugin { def version = "0.1"… }
このようなクラスがプラグインディレクトリのルートに存在しなければなりません。このプラグインクラスは、プラグインのバージョン情報や他のメタデータを定義しています。さらに、プラグイン拡張ポイントへの様々なフックを定義することができます(簡易にカバー)。
さらに、いくつかの特別なプロパティを使って、プラグインの追加情報を提供することもできます。
title
- short one-sentence description of your pluginversion
- The version of your plugin. Valid values include example "0.1", "0.2-SNAPSHOT", "1.1.4" etc.grailsVersion
- The version of version range of Grails that the plugin supports. eg. "1.2 > *" (indicating 1.2 or higher)author
- plugin author's nameauthorEmail
- plugin author's contact e-maildescription
- full multi-line description of plugin's featuresdocumentation
- URL of the plugin's documentation
title
- このプラグインを説明する短い一文。version
- このプラグインのバージョン。例えば「0.1」「0.2-SNAPSHOT」「1.1.4」などの有効な値。grailsVersion
- プラグインがサポートするGrailsのバージョンを、バージョン範囲で指定する。例えば「1.2 > *」(これは「1.2以上」であることを示す)author
- プラグインの開発者名authorEmail
- プラグイン開発者に連絡するためのe-mailアドレスdescription
- 複数行に渡るプラグイン機能のフル説明documentation
- プラグインのドキュメントへのURL
class QuartzGrailsPlugin { def version = "0.1" def grailsVersion = "1.1 > *" def author = "Sergey Nebolsin" def authorEmail = "nebolsin@gmail.com" def title = "Quartz Plugin" def description = '''\ The Quartz plugin allows your Grails application to schedule jobs\ to be executed using a specified interval or cron expression. The\ underlying system uses the Quartz Enterprise Job Scheduler configured\ via Spring, but is made simpler by the coding by convention paradigm.\ ''' def documentation = "http://grails.org/plugin/quartz"… }
Installing Local Plugins
To make your plugin available for use in a Grails application run the maven-install
command:
grails maven-install
This will install the plugin into your local Maven cache. Then to use the plugin within an application declare a dependency on the plugin in your grails-app/conf/BuildConfig.groovy
file:
compile
Notes on excluded Artefacts
アーテファクト除外についての留意事項
前述のように、create-pluginコマンドはプラグインプロジェクトとして一連のファイルを作成し、Grailsアプリケーションとして実行することもできますが、パッケージ化したときにこれら全てのファイルが含められるわけではありません。以下は、生成されるけれども、package-pluginコマンドで生成されるzipファイルには含まれないアーテファクトのリストです。
grails-app/conf/BootStrap.groovy
grails-app/conf/BuildConfig.groovy
(although it is used to generatedependencies.groovy
)grails-app/conf/Config.groovy
grails-app/conf/DataSource.groovy
(and any other*DataSource.groovy
)grails-app/conf/UrlMappings.groovy
grails-app/conf/spring/resources.groovy
- Everything within
/web-app/WEB-INF
- Everything within
/web-app/plugins/**
- Everything within
/test/**
- SCM management files within
**/.svn/**
and**/CVS/**
grails-app/conf/BootStrap.groovy
grails-app/conf/BuildConfig.groovy
(dependencies.groovy
の生成には使用される)grails-app/conf/Config.groovy
grails-app/conf/DataSource.groovy
(これと他の任意の*DataSource.groovy
)grails-app/conf/UrlMappings.groovy
grails-app/conf/spring/resources.groovy
/web-app/WEB-INF
配下のすべて/web-app/plugins/**
配下のすべて/test/**
配下のすべて**/.svn/**
と**/CVS/**
配下のSCM管理ファイル
WEB-INF
it is recommended you use the _Install.groovy
script (covered later), which is executed when a plugin is installed, to provide such artefacts. In addition, although UrlMappings.groovy
is excluded you are allowed to include a UrlMappings
definition with a different name, such as MyPluginUrlMappings.groovy
.
アーテファクトをWEB-INF
に含める必要がある場合には、プラグインインストール時に実行されるスクリプトである_Install.groovy
スクリプト(後述)を使用することがお勧めです。なお、除外対象アーティファクトであるUrlMappings.groovy
は除外されますが、UrlMappings
情報は「MyPluginUrlMappings.groovy
」などの異なる名前にしておけば、含めることができます。
Customizing the plugin contents
You can specify what to exclude in addition to the default excludes by adding elements to the pluginExcludes
descriptor property (described below). In addition, there are two ways to configure the contents of the plugin ZIP or JAR file.
One is to create an event handler for the CreatePluginArchiveStart
event, which is fired after all of the plugin files have been copied to the staging directory. By adding an event handler you can add, modify, or delete files as needed. Add the handler to _Events.groovy
in the scripts
directory, for example
eventCreatePluginArchiveStart = { stagingDir -> // update staging directory contents here }
You can customize the location of the staging directory with the grails.project.plugin.staging.dir
attribute in BuildConfig.groovy
or as as system property.
Note that there is also a CreatePluginArchiveEnd
event which is fired after the ZIP or JAR is packaged.
You can also do this work in a Closure in BuildConfig.groovy
with the property grails.plugin.resources
which is analogous to the grails.war.resources
property, e.g.
grails.plugin.resources = { stagingDir -> // update staging directory contents here }
Specifying Plugin Locations
プラグイン位置の指定
grails-app/conf/BuildConfig.groovy
file:
アプリケーションは、ファイルシステム上の任意の場所にあるプラグインをロードできますし、インストールしていないプラグインをロードすることさえも可能です。そのためには、アプリケーションのgrails-app/conf/BuildConfig.groovy
設定ファイルに、パッケージされていないプラグインのディレクトリを以下のように指定します:
// Useful to test plugins you are developing. grails.plugin.location.shiro = "/home/dilbert/dev/plugins/grails-shiro"// Useful for modular applications where all plugins and // applications are in the same directory. grails.plugin.location.'grails-ui' = "../grails-grails-ui"
// 開発中のプラグインをテストするのに便利。 grails.plugin.location.shiro = "/home/dilbert/dev/plugins/grails-shiro"// すべてのプラグインとアプリケーションを同じディレクトリに置き、 // モジュール化するのに便利。 grails.plugin.location.'grails-ui' = "../grails-grails-ui"
- You are developing a plugin and want to test it in a real application without packaging and installing it first.
- You have split an application into a set of plugins and an application, all in the same "super-project" directory.
これが特に便利なのは、以下の2つの場合です:
- 開発中のプラグインを、パッケージ化とインストールをスキップして、実アプリケーションにすぐに組み込んでテストしたいとき。
- アプリケーションが複数のプラグイン群に分割されており、それらすべてが同じ「スーパープロジェクト」ディレクトリ配下にある場合。
The Artifactory repository for Grails now includes all the dependencies for published plugins. So, if you are using inline plugins that have dependencies, it is necessary to do a secondary resolve because these dependencies might not be in the repository. Therefore, you should setlegacyResolve
totrue
in yourBuildConfig.groovy
if you are using inline plugins with dependencies.
15.2 プラグインリポジトリ
プラグインをGrailsセントラルリポジトリに公開する
grails list-plugins
このコマンドはセントラルリポジトリのすべてのプラグインを一覧表示します。あなたのプラグインをplugin-infoコマンドで表示することもできます:
grails plugin-info [plugin-name]
これで説明や著者名、その他のプラグイン情報などを表示させることができます。
If you have created a Grails plugin and want it to be hosted in the central repository, you'll find instructions for getting an account on this wiki page.
もしGrailsプラグインを開発して、セントラルリポジトリでホスティングしたい場合、アカウント入手の手順はこのWikiページにあります。
grails-app/conf/BuildConfig.groovy
file:Grailsプラグインリポジトリにアクセス権を持っていれば、リリースプラグインを grails-app/conf/BuildConfig.groovy
ファイルの依存管理'build'スコープに定義してインストールします。
grails.project.dependency.resolution = { … plugins { build ':release:3.0.0' } }
And execute the publish-plugin
command to release your plugin:
grails publish-plugin
This will automatically publish the plugin to the central repository. If the command is successful, it will immediately be available on the plugin portal at http://grails.org/plugin/<pluginName>. You can find out more about the Release plugin and its other features in its user guide.
追加リポジトリの設定
Grailsにおけるリポジトリの設定手順は、Grailsのバージョンによって異なっています。Grails 1.2以前の情報についてはGrails 1.2のドキュメンテーションを参照ください。以降の節は、Grails 1.3以降について記述しています。
grails-app/conf/BuildConfig.groovy
:Grails 1.3以上では、下位層に隠されているIvyがプラグインの依存性を解決します。プラグインリポジトリを追加定義する仕組みは、 JAR依存性を定義する方法とほぼ同じです。例えば、Grailsプラグインを含むリモートMavenリポジトリを定義するには、 grails-app/conf/BuildConfig.groovy
中で以下のように記述します:
repositories { mavenRepo "http://repository.codehaus.org"// ...or with a name mavenRepo name: "myRepo", root: "http://myserver:8081/artifactory/plugins-snapshots-local" }
grailsRepo
method:grailsRepo
メソッドを使ってSVNベースのGrailsリポジトリ(例えばhttp://plugins.grails.orgでホストされているリポジトリ)を定義することもできます:
repositories { grailsRepo "http://myserver/mygrailsrepo"// ...or with a name grailsRepo "http://myserver/svn/grails-plugins", "mySvnRepo" }
repositories { grailsCentral() }
repositoriesの項目で列挙した順にプラグインは解決されます。なので以下ではGrailsセントラルリポジトリが最後に検索されます:
repositories {
grailsRepo "http://myserver/mygrailsrepo"
grailsCentral()
}
前述の例ではHTTPを使用していましたが、プラグイン解決に任意のIvyリゾルバを使用することもできます。以下はSSHリゾルバを使用する例です:
def sshResolver = new SshResolver(user:"myuser", host:"myhost.com") sshResolver.addArtifactPattern( "/path/to/repo/grails-[artifact]/tags/" + "LATEST_RELEASE/grails-[artifact]-[revision].[ext]") sshResolver.latestStrategy = new org.apache.ivy.plugins.latest.LatestTimeStrategy()sshResolver.changingPattern = ".*SNAPSHOT" sshResolver.setCheckmodified(true)
上記の例では、プラグインZIPファイルを解決する方法をIvyに伝えるため、アーテファクトのパターンを指定しています。Ivyパターンのより詳しい説明は、Ivyユーザガイドの関連するセクションを参照下さい。
Maven互換リポジトリへの公開
In general it is recommended for Grails 1.3 and above to use standard Maven-style repositories to self host plugins. The benefits of doing so include the ability for existing tooling and repository managers to interpret the structure of a Maven repository.
You use the Release plugin to publish a plugin to a Maven repository. Please refer to the section of the Maven deployment user guide on the subject.
15.3 プラグイン構造を理解する
すでに述べてきているように、プラグインは基本的にはプラグインディスクリプタが付随した通常のGrailsアプリケーションです。しかしながら、インストールされるときにはプラグインの構造は少し異なってきます。例えば、以下のプラグイン構造を見てみましょう:
+ grails-app + controllers + domain + taglib etc. + lib + src + java + groovy + web-app + js + css
grails-app
directory will go into a directory such as plugins/example-1.0/grails-app
. They will not be copied into the main source tree. A plugin never interferes with a project's primary source tree.プラグインがインストールされたときには、grails-app
ディレクトリの内容はplugins/example-1.0/grails-app
に入ります。これらはメインアプリのソースツリーにはインストールされません。プラグインはプロジェクト本体側のソースツリーには決して干渉しないのです。
web-app
directory. You can then link to static resources just like in an application. This example links to a JavaScript source:静的リソースの処理は、少しだけ異なってきます。プラグインをあたかもアプケーションのように開発する際、すべての静的リソースはweb-app
ディレクトリに入ります。静的リソースをアプリケーションからリンクすることもできます。以下の例ではJavaScriptソースをリンクしています:
<g:resource dir="js" file="mycode.js" />
/js/mycode.js
. However, when the plugin is installed into an application the path will automatically change to something like /plugin/example-0.1/js/mycode.js
and Grails will deal with making sure the resources are in the right place.プラグインを開発モード(development mode)で実行するときは、このようなリソースへのリンクは/js/mycode.js
などに解決されます。しかし、プラグインがアプリケーションにインストールされたときは、パスは自動的に/plugin/example-0.1/js/mycode.js
のように自動的に変換され、Grailsはリソースを正しく扱うことができます。
pluginContextPath
variable that can be used whilst both developing the plugin and when in the plugin is installed into the application to find out what the correct path to the plugin is.プラグイン開発モードと、プラグインがアプリケーションにインストールされている場合のいずれにおいても、plugin.jsの正しいパスを見付けるのに、そのためのpluginContextPath
変数を使用できます。
pluginContextPath
variable will either evaluate to an empty string or /plugins/example
depending on whether the plugin is running standalone or has been installed in an applicationスタンドアローン実行中かアプリケーションにインストールされているかによって、pluginContextPath
変数は空文字列もしくは/plugins/example
のいずれかに実行時に評価されます。
src/java
and src/groovy
directories will be compiled into the main project's web-app/WEB-INF/classes
directory so that they are made available at runtime.プラグインが提供する、libやsrc/java
やsrc/groovy
ディレクトリ配下にあるJavaやGroovyコードは、実行時に利用できるようにメインプロジェクトのweb-app/WEB-INF/classes
ディレクトリ配下にコンパイルされます。
15.4 基本アーティファクトの提供
新たにスクリプトを追加する
プラグインのscriptディレクトリ配下に関連するGantスクリプトを置くことで、プラグインは新しいスクリプトを追加することができます:
+ MyPlugin.groovy + scripts <-- additional scripts here + grails-app + controllers + services + etc. + lib
+ MyPlugin.groovy + scripts <-- ここにスクリプトを追加する + grails-app + controllers + services + etc. + lib
Grails-appアーテファクト(Controller, Tag Library, Service, 他)の追加
grails-app
tree. Note that the plugin is loaded from where it is installed and not copied into the main application tree.grails-app
配下のツリーに関連するファイルを置いておくことで、プラグインは新しいアーテファクトを追加することができます。プラグインはインストールされた場所から読み込まれるのであって、メインアプリのツリー中にコピーされるわけではないことに留意して下さい。
+ ExamplePlugin.groovy + scripts + grails-app + controllers <-- コントローラを追加するのはここ。 + services <-- サービスを追加するのはここ。 + etc. <-- 他も同様。 + lib
ビューとテンプレートの提供、そしてビューの解決
grails-app/views
directory.プラグインがコントローラを提供するときは、レンダリングされるデフォルトのビューを提供しても構いません。これはアプリケーションをプラグインに分割するのに優れた方法です。
Grailsのビュー解決機構は、最初にプラグインがインストールされた親アプリケーション中のビューを探し、見付からなければプラグイン自身のビューを探してみます。これが意味するのは、アプリケーションのgrails-app/views
ディレクトリ中に対応するGSPを定義しておくことで、プラグインが提供するビューを上書きすることができるということです。
BookController
that's provided by an 'amazon' plugin. If the action being executed is list
, Grails will first look for a view called grails-app/views/book/list.gsp
then if that fails it will look for the same view relative to the plugin.例えば、「アマゾン」プラグインが提供するBookController
を考えてみて下さい。もしlist
アクションが実行されたなら、Grailsは最初にgrails-app/views/book/list.gsp
を検索し、それに失敗した場合にプラグインディレクトリから相対的に同じ位置にあるビューを検索します。
しかしながら、同じくプラグインが提供するテンプレートをビューが使用しているときには、以下の構文が必要になります:
<g:render template="fooTemplate" plugin="amazon"/>
plugin
attribute, which contains the name of the plugin where the template resides. If this is not specified then Grails will look for the template relative to the application.plugin
属性でテンプレートがあるプラグインの名前を指定することに注意下さい。もしこれがなければ、Grailsはアプリケーション相対でテンプレートを探します。
アーテファクトを除外する
デフォルトでは、Grailsはプラグインのパッケージングの過程で以下のファイルを除外します:
grails-app/conf/BootStrap.groovy
grails-app/conf/BuildConfig.groovy
(although it is used to generatedependencies.groovy
)grails-app/conf/Config.groovy
grails-app/conf/DataSource.groovy
(and any other*DataSource.groovy
)grails-app/conf/UrlMappings.groovy
grails-app/conf/spring/resources.groovy
- Everything within
/web-app/WEB-INF
- Everything within
/web-app/plugins/**
- Everything within
/test/**
- SCM management files within
**/.svn/**
and**/CVS/**
grails-app/conf/BootStrap.groovy
grails-app/conf/BuildConfig.groovy
(この情報はdependencies.groovy
の生成に用いられるが、BuildConfig自体は含められない)grails-app/conf/Config.groovy
grails-app/conf/DataSource.groovy
(その他の*DataSource.groovy
も同様)grails-app/conf/UrlMappings.groovy
grails-app/conf/spring/resources.groovy
/web-app/WEB-INF
中のすべて/web-app/plugins/**
中のすべて/test/**
中のすべて**/.svn/**
と**/CVS/**
中のSCMが管理するファイル
web-app/WEB-INF
directory it is recommended that you modify the plugin's scripts/_Install.groovy
Gant script to install these artefacts into the target project's directory tree.もしプラグインがweb-app/WEB-INF
ディレクトリ配下のファイルを必要とするなら、プラグインディレクトリのscripts/_Install.groovy
Gantスクリプトを修正し、それらのアーテファクトをターゲットのプロジェクトのディレクトリツリーにコピーするようにすることをお勧めします。
UrlMappings.groovy
file is excluded to avoid naming conflicts, however you are free to add a UrlMappings definition under a different name which will be included. For example a file called grails-app/conf/BlogUrlMappings.groovy
is fine.加えて、名前衝突を避けるため、デフォルトではUrlMappings.groovy
ファイルは除外されていますが、「UrlMapping」が含まれる異なる名前のUrlMappings定義を追加するのは構いません。例えば、grails-app/conf/BlogUrlMappings.groovy
などの名前にしておくと良いでしょう。
pluginExcludes
property:除外リストはpluginExcludes
プロパティで拡張することができます:
// resources that are excluded from plugin packaging
def pluginExcludes = [
"grails-app/views/error.gsp"
]
// プラグインのパッケージングからは除外するリソース
def pluginExcludes = [
"grails-app/views/error.gsp"
]
この指定は、デモやテスト用リソースとしてプラグインのソースリポジトリには含めたいが、プラグインとしての最終配布物には含めたくない、という場合に有用でしょう。
15.5 規約の評価
application
variable which is an instance of the GrailsApplication interface.Grailsが提供する、規約ベースのランタイム設定を見ていく前に、あなたが理解しておくべきことは、これらのプラグインの規約がどう評価されるか、ということです。どのプラグインも、暗黙のapplication
変数を持っていて、これはGrailsApplicationのインスタンスです。
GrailsApplication
interface provides methods to evaluate the conventions within the project and internally stores references to all artifact classes within your application.このGrailsApplication
インターフェースは、プロジェクト中の規約を評価するためのメソッドを提供します。また、内部的にあなたのアプリのすべてのアーテファクトクラスへの参照を保存します。
GrailsClass
instances you can do:アーテファクトはGrailsClassインターフェースを実装し、コントローラやタグライブラリのようなGrailsのリソースを表現します。例えばすべてのGrailsClass
インスタンスを取得するには以下のようにします:
for (grailsClass in application.allClasses) {
println grailsClass.name
}
GrailsApplication
has a few "magic" properties to narrow the type of artefact you are interested in. For example to access controllers you can use:GrailsApplication
はいくつかの「マジック」プロパティを持っていて、あなたの興味があるアーテファクトの型を狭めることができます。例えば、コントローラにアクセスするには以下のようにできます:
for (controllerClass in application.controllerClasses) {
println controllerClass.name
}
*Classes
- Retrieves all the classes for a particular artefact name. For exampleapplication.controllerClasses
.get*Class
- Retrieves a named class for a particular artefact. For exampleapplication.getControllerClass("PersonController")
is*Class
- Returnstrue
if the given class is of the given artefact type. For exampleapplication.isControllerClass(PersonController)
*Classes
- 特定のアーテファクト名のすべてのクラスを取り出す。 例えばapplication.controllerClasses
。get*Class
- 特定のアーテファクトの、指定した名前のクラスを取り出す。 例えばapplication.getControllerClass("PersonController")
。is*Class
- もし指定したクラスが指定したアーテファクトタイプであればtrue
を返す。 例えば、application.isControllerClass(PersonController)
。
GrailsClass
interface has a number of useful methods that let you further evaluate and work with the conventions. These include:GrailsClass
インターフェースは、規約に関する評価や処理をさらに容易にするための、以下のような便利なメソッド群を持っています:
getPropertyValue
- Gets the initial value of the given property on the classhasProperty
- Returnstrue
if the class has the specified propertynewInstance
- Creates a new instance of this class.getName
- Returns the logical name of the class in the application without the trailing convention part if applicablegetShortName
- Returns the short name of the class without package prefixgetFullName
- Returns the full name of the class in the application with the trailing convention part and with the package namegetPropertyName
- Returns the name of the class as a property namegetLogicalPropertyName
- Returns the logical property name of the class in the application without the trailing convention part if applicablegetNaturalName
- Returns the name of the property in natural terms (eg. 'lastName' becomes 'Last Name')getPackageName
- Returns the package name
getPropertyValue
- そのクラスの指定したプロパティの初期値を取得する。hasProperty
- もしクラスが指定したプロパティを持っていたらtrue
を返す。newInstance
- このクラスの新しいインスタンスを返す。getName
- 取得可能であれば、末尾の規約部分を除いた、アプリケーションにおける論理名を返す。getShortName
- そのクラスのパッケージ接頭辞を除いた短縮名を返す。getFullName
- 末尾の規約部分と先頭のパッケージ部分を含むクラスのフルネームを返す。getPropertyName
- クラス名をプロパティ名として返す。getLogicalPropertyName
- 末尾の規約部分を除き、アプリケーションにおけるクラスの論理プロパティ名を返す。getNaturalName
- 自然な語句としてのプロパティ名を返す。(例: 'lastName'は'Last Name'になる)getPackageName
- パッケージ名を返す。
全体のリファレンスについては、javadoc APIを参照してください。
15.6 ビルドイベントのフック
Post-Install設定とアップグレード
scripts
directory of the plugin - _Install.groovy
and _Upgrade.groovy
.Grailsプラグインはpost-install設定を行なったり、アプリケーションの更新プロセス(upgradeコマンドで実行する)に介在することができます。これは2つの特別な名前のスクリプト、_Install.groovy
と_Upgrade.groovy
スクリプトを、プラグインのscripts
ディレクトリ配下に置くことで可能になります。
_Install.groovy
is executed after the plugin has been installed and _Upgrade.groovy
is executed each time the user upgrades the application (but not the plugin) with upgrade command._Install.groovy
はプラグインがインストールされた後に実行され、_Upgrade.groovy
コマンドはアプリケーションが upgradeコマンドで更新されるたびに実行されます(プラグインをupgradeコマンドで更新した時ではありません)。
pluginBasedir
variable which points at the plugin installation basedir.これらのスクリプトは、Gantスクリプトであり、Gantの全機能を使用することができます。標準Gant変数に加えて、pluginBasedir
変数があり、プラグインがインストールされているベースディレクトリを指定しています。
_Install.groovy
script will create a new directory type under the grails-app
directory and install a configuration template:例えば、以下の_Install.groovy
スクリプトはgrails-app
ディレクトリ配下に新しいディレクトリを作成し、設定テンプレートをインストールします:
ant.mkdir(dir: "${basedir}/grails-app/jobs")ant.copy(file: "${pluginBasedir}/src/samples/SamplePluginConfig.groovy", todir: "${basedir}/grails-app/conf")
pluginBasedir
variable is not available in custom scripts, but you can use fooPluginDir
, where foo
is the name of your plugin.pluginBasedir
変数はカスタムスクリプト中では利用できませんが、foo
がプラグイン名であるとき、fooPluginDir
を使うことができます。
イベントをスクリプトで処理する
コマンドラインスクリプトを実行中のイベントをフックすることもできます。Grailsターゲットとプラグインスクリプトの実行中に発生するイベントがあります。
例えば、状態の変更イベント(「テストがパスしたとき」や「サーバが実行開始」など)や、ファイルやアーテファクトの生成イベントなどにもフックすることができます。
_Events.groovy
script to listen to the required events. Refer the documentation on Hooking into Events for further information.プラグインが必要なイベントをlistenするために必要なのは、_Events.groovy
スクリプトを提供することだけです。より詳しい情報については、イベントをフックするを参照してください。
15.7 ランタイム設定へのフック
Grailsはシステムの異なる部分を利用するために、多くのフックを提供し、規約によって実行時設定を行います。
GrailsのSpring設定にフックする
doWithSpring
which is assigned a block of code. For example the following snippet is from one of the core Grails plugins that provides i18n support:まず、doWithSpring
という名前の、クロージャブロックが代入されたプロパティを提供することで、Grails実行時設定にフックすることができます。例えば以下のコード断片は、 i18nサポートを提供するコアGrailsプラグインに含まれているものです:
import org.springframework.web.servlet.i18n.CookieLocaleResolver import org.springframework.web.servlet.i18n.LocaleChangeInterceptor import org.springframework.context.support.ReloadableResourceBundleMessageSourceclass I18nGrailsPlugin {
def version = "0.1"
def doWithSpring = { messageSource(ReloadableResourceBundleMessageSource) { basename = "WEB-INF/grails-app/i18n/messages" } localeChangeInterceptor(LocaleChangeInterceptor) { paramName = "lang" } localeResolver(CookieLocaleResolver) } }
messageSource
bean and a couple of other beans to manage Locale resolution and switching. It using the Spring Bean Builder syntax to do so.このプラグインは、GrailsのmessageSource
ビーンと、Locale解決と切り替えを行う他のいくつかのビーンを設定します。これはSpringビーンビルダのシンタックスを使用します。
web.xml生成への参加
WEB-INF/web.xml
file at load time, and although plugins cannot change this file directly, they can participate in the generation of the file. A plugin can provide a doWithWebDescriptor
property that is assigned a block of code that gets passed the web.xml
as an XmlSlurper
GPathResult
.GrailsはWEB-INF/web.xml
ファイルをロード時に生成し、プラグインはこのファイルを直接変更することはできませんが、このファイルの生成過程に参加することができます。プラグインはクロージャコードブロックが代入されたdoWithWebDescriptor
プロパティを提供することができ、そのコードにはXmlSlurper
のGPathResult
としてweb.xml
が渡されます。
servlet
and servlet-mapping
servlet
とservlet-mapping
の追加
ControllersPlugin
:ControllersPlugin
にある、以下の例を考えてみてください:
def doWithWebDescriptor = { webXml ->def mappingElement = webXml.'servlet-mapping'
def lastMapping = mappingElement[mappingElement.size() - 1] lastMapping + { 'servlet-mapping' { 'servlet-name'("grails") 'url-pattern'("*.dispatch") } } }
<servlet-mapping>
element and appends Grails' servlet after it using XmlSlurper's ability to programmatically modify XML using closures and blocks.XmlSlurperの「クロージャとブロックを使ってプログラム的にXMLを修正できる」という機能を使って、ここではプラグインは<servlet-mapping>
への参照を取得し、Grailsのサーブレットを追加しています。
filter
and filter-mapping
filter
とfilter-mapping
の追加
<filter>
element doesn't matter since order is not important, so it's simplest to insert your custom filter definition immediately after the last <context-param>
element. Order is important for mappings, but the usual approach is to add it immediately after the last <filter>
element like so:マッピングを伴うフィルターの追加は少し異なります。順序は重要ではないので、<filter>
要素の場所は問題になりません。なのでカスタムフィルタ定義を最後の<context-param>
要素のすぐ後に挿入するのが最も簡単です。マッピングに関しては 順序は重要 です。しかし通常の場合、<filter>
要素の直後に追加してしまいます:
def doWithWebDescriptor = { webXml ->def contextParam = webXml.'context-param'
contextParam[contextParam.size() - 1] + { 'filter' { 'filter-name'('springSecurityFilterChain') 'filter-class'(DelegatingFilterProxy.name) } }
def filter = webXml.'filter' filter[filter.size() - 1] + { 'filter-mapping'{ 'filter-name'('springSecurityFilterChain') 'url-pattern'('/*') } } }
フィルターは、例えばSpringの文字エンコーディングフィルタやSiteMeshフィルタなどの標準Grailsフィルターの後に実行されなければならない場合があります。この場合、以下のようにすることで、フィルタマッピングを標準のフィルタ(正確に言えば、テンプレートのweb.xmlファイルに含まれている任意のもの)のすぐ後に挿入することができます:
def doWithWebDescriptor = { webXml -> ...// Insert the Spring Security filter after the Spring // character encoding filter. def filter = webXml.'filter-mapping'.find { it.'filter-name'.text() == "charEncodingFilter" }
filter + { 'filter-mapping'{ 'filter-name'('springSecurityFilterChain') 'url-pattern'('/*') } } }
初期化設定後の実行
doWithApplicationContext
closure property.ApplicationContextが構築された後で実行時設定を行うことが有用な場合があります。そのためにはdoWithApplicationContext
クロージャプロパティを定義します。
class SimplePlugin {def name = "simple" def version = "1.1"
def doWithApplicationContext = { appCtx -> def sessionFactory = appCtx.sessionFactory // do something here with session factory } }
15.8 実行時のダイナミックメソッド追加
基本的な考え方
doWithDynamicMethods
closure.Grailsプラグインでは、Grails管理下および他のクラスに対して、実行時にダイナミックメソッドを登録することができます。これはdoWithDynamicMethods
クロージャで行ないます。
コントローラやタグライブラリなどのようなGrails管理下のクラスについては、それぞれのコントローラのMetaClassを ExpandoMetaClass の機構でアクセスすることによって、メソッドやコンストラクタなどを追加できます:
class ExamplePlugin { def doWithDynamicMethods = { applicationContext -> for (controllerClass in application.controllerClasses) { controllerClass.metaClass.myNewMethod = {-> println "hello world" } } } }
myNewMethod
to each controller. If you know beforehand the class you wish the add a method to you can simply reference its metaClass
property.この場合、暗黙のapplicationオブジェクトを使い、すべてのコントローラクラスのMetaClassの参照を取得し、それぞれのコントローラにmyNewMethod
という新規メソッドを追加しています。メソッドを追加したいクラスが予め判っていれば、そのmetaClass
プロパティを単純に参照できます。
swapCase
to java.lang.String
:例えば、swapCase
メソッドをjava.lang.String
クラスに追加できます:
class ExamplePlugin {def doWithDynamicMethods = { applicationContext -> String.metaClass.swapCase = {-> def sb = new StringBuilder() delegate.each { sb << (Character.isUpperCase(it as char) ? Character.toLowerCase(it as char) : Character.toUpperCase(it as char)) } sb.toString() }
assert "UpAndDown" == "uPaNDdOWN".swapCase() } }
アプリケーションコンテキストとの相互作用
doWithDynamicMethods
closure gets passed the Spring ApplicationContext
instance. This is useful as it lets you interact with objects within it. For example if you were implementing a method to interact with Hibernate you could use the SessionFactory
instance in combination with a HibernateTemplate
:doWithDynamicMethods
クロージャにはSpringのApplicationContext
インスタンスが渡されます。これはその中のオブジェクトとやりとりできるので便利です。例えば、Hibernateと相互作用するメソッドを定義しているなら、SessionFactory
インスタンスとHibernateTemplate
を組合せて使うことができます:
import org.springframework.orm.hibernate3.HibernateTemplateclass ExampleHibernatePlugin {
def doWithDynamicMethods = { applicationContext ->
for (domainClass in application.domainClasses) {
domainClass.metaClass.static.load = { Long id-> def sf = applicationContext.sessionFactory def template = new HibernateTemplate(sf) template.load(delegate, id) } } } }
Springコンテナにはオートワイアリング(autowiring)と依存性注入(DI)機能があるので、依存性を実行時に解決するのにアプリケーションコンテキストを使用する、より強力なダイナミックコンストラクタをあなたのオブジェクトに実装することもできます:
class MyConstructorPlugin {def doWithDynamicMethods = { applicationContext -> for (domainClass in application.domainClasses) { domainClass.metaClass.constructor = {-> return applicationContext.getBean(domainClass.name) } } } }
ここでは、デフォルトコンストラクタを、prototypeのSpringビーンをルックアップするようなコンストラクタに実際に置き換えています。
15.9 自動リロードイベントへの参加
リソース変更の監視
ServicesPlugin
:リソース変更を監視し、変更された場合に何らかのアクションを実行することが便利なときがあります。この方法を用いて、Grailsではアプリケーションの状態が実行時に変化したときに高度なリローディングを行っています。例えば、ServicesPlugin
のにあるものを単純化した以下のコード断片を見てください:
class ServicesGrailsPlugin { … def watchedResources = "file:./grails-app/services/*Service.groovy"… def onChange = { event -> if (event.source) { def serviceClass = application.addServiceClass(event.source) def serviceName = "${serviceClass.propertyName}" def beans = beans { "$serviceName"(serviceClass.getClazz()) { bean -> bean.autowire = true } } if (event.ctx) { event.ctx.registerBeanDefinition( serviceName, beans.getBeanDefinition(serviceName)) } } } }
watchedResources
as either a String or a List of strings that contain either the references or patterns of the resources to watch. If the watched resources specify a Groovy file, when it is changed it will automatically be reloaded and passed into the onChange
closure in the event
object.最初にwatchedResources
変数を定義していますが、これは監視対象としたいリソースへの参照もしくはパターンを含む、文字列もしくは文字列のリストです。もし監視されるリソースがGroovyファイルを指定しているのであれば、それが変更されたときには自動的にリロードが実行されます。そして、onChange
クロージャが呼び出され、Groovyファイルはその引数であるevent
オブジェクト中に設定されます:
event
object defines a number of useful properties:event
オブジェクトは多数の有用なプロパティを含んでいます:
event.source
- The source of the event, either the reloadedClass
or a SpringResource
event.ctx
- The SpringApplicationContext
instanceevent.plugin
- The plugin object that manages the resource (usuallythis
)event.application
- TheGrailsApplication
instanceevent.manager
- TheGrailsPluginManager
instance
event.source
- イベントの発生元。リロードされたClass
もしくはSpringResource
。event.ctx
- SpringApplicationContext
インスタンスevent.plugin
- このリソースを管理しているプラグインオブジェクト(通常this
)。event.application
-GrailsApplication
インスタンスevent.manager
-GrailsPluginManager
インスタンス
ApplicationContext
when one of the service classes changes.何が変更されたかによって異なる適切な変更をするためには、これらのオブジェクトが利用可能です。前述のサービスの例においては、サービスクラスが変更されたとき、新しいサービスビーンがApplicationContext
において再登録されます。
他のプラグインに影響を及ぼす
変更に対してリアクションするのに加え、プラグインは他のプラグインに「影響を及ぼす」必要があるときがあります。
サービスとコントローラのプラグインを例にとりましょう。サービスがリロードされた場合、コントローラもリロードしなければ、リロードされたサービスを古いコントローラクラスにオートワイヤ(auto-wire)するときに問題が発生するでしょう。
ServicesGrailsPlugin
:この問題を回避するために、どのプラグインが他のプラグインに「影響を及ぼす」のかを指定することができます。これが意味するのは、あるプラグインが変更を検出したとき、そのプラグイン自身がリロードされた後に、それが「影響を及ぼしている」プラグインもリロードされるということです。例えば、ServicesGrailsPlugin
にある以下のコード断片を考えてみましょう:
def influences = ['controllers']
他のプラグインを観察する
変更を観察したい特定のプラグインがあり、そのプラグインが監視するリソースを監視する必要がないなら、「observe」プロパティを使うことができます:
def observe = ["controllers"]
この場合、コントローラが変更されたとき、あなたのプラグインもコントローラプラグインから連鎖したイベントを受け取ります。
ワイルドカードを使えば、すべてのプラグインの変更を監視することも可能です:
def observe = ["*"]
log
property back to any artefact that changes while the application is running.ロギングプラグインはちょうどこのようなことを行なっており、アプリの実行中に変更があった 任意の アーティファクトにlog
プロパティを設定し直しています。
15.10 プラグインのロード順を理解する
プラグインの依存性制御
dependsOn
. For example, take a look at this snippet from the Hibernate plugin:プラグインはしばしば他のプラグインの存在に依存しますが、他のプラグインの存在についての依存性に適応することができます。これは2つのプロパティで行うことができます。1つ目はdependsOn
というプロパティですが、Hibernateプラグインにある以下のコード断片を見て下さい:
class HibernateGrailsPlugin {def version = "1.0"
def dependsOn = [dataSource: "1.0", domainClass: "1.0", i18n: "1.0", core: "1.0"] }
dataSource
, domainClass
, i18n
and core
plugins.Hibernateプラグインは4つのプラグインに依存しています: dataSource
、domainClass
、i18n
そしてcore
プラグインです。
依存しているプラグインは、Hibernateプラグインの前に読み込まれます。すべての依存プラグインがロードされなければ、プラグインはロードされません。
dependsOn
property also supports a mini expression language for specifying version ranges. A few examples of the syntax can be seen below:dependsOn
プロパティはバージョン範囲を指定するためのミニ式言語をサポートしています。以下は例です:
def dependsOn = [foo: "* > 1.0"] def dependsOn = [foo: "1.0 > 1.1"] def dependsOn = [foo: "1.0 > *"]
ワイルドカード文字が任意のバージョンを表わすために使われます。また、この式のシンタックスは、「-BETA」や「-ALPHA」といった接尾辞を除外します。なので例えば「1.0 > 1.1」は以下のバージョンにマッチします。
- 1.1
- 1.0
- 1.0.1
- 1.0.3-SNAPSHOT
- 1.1-BETA2
ロード順序の制御
dependsOn
establishes a "hard" dependency in that if the dependency is not resolved, the plugin will give up and won't load. It is possible though to have a weaker dependency using the loadAfter
and loadBefore
properties:dependsOn
は、依存性が解決されなければプラグインのロードをあきらめるような「ハード依存性」を確立します。loadAfter
とloadBefore
プロパティを使うことで「より弱い依存性」を使うこともできます。
def loadAfter = ['controllers']
controllers
plugin if it exists, otherwise it will just be loaded. The plugin can then adapt to the presence of the other plugin, for example the Hibernate plugin has this code in its doWithSpring
closure:ここでは、もしcontrollers
プラグインが存在すれば、それがロードされた後に、このプラグインがロードされます。 さもなければ(controllers
プラグインが存在しなければ)、このプラグインは単にロードされます。プラグインは他のプラグインの存在に適応します。たとえば、HibernateプラグインはdoWithSpring
クロージャで以下を行っています:
if (manager?.hasGrailsPlugin("controllers")) { openSessionInViewInterceptor(OpenSessionInViewInterceptor) { flushMode = HibernateAccessor.FLUSH_MANUAL sessionFactory = sessionFactory } grailsUrlHandlerMapping.interceptors << openSessionInViewInterceptor }
OpenSessionInViewInterceptor
if the controllers
plugin has been loaded. The manager
variable is an instance of the GrailsPluginManager interface and it provides methods to interact with other plugins.ここではHibernateプラグインは、controllers
プラグインがロードされてれば、OpenSessionInViewInterceptor
だけを登録します。manager
変数はGrailsPluginManagerインターフェースのインスタンスであり、他のプラグインと相互作用するためのメソッドを提供しています。
loadBefore
property to specify one or more plugins that your plugin should load before:loadBefore
プロパティには、あなたのプラグインの前にロードしておかなければならない1個以上のプラグインを指定します。
def loadBefore = ['rabbitmq']
スコープと環境
制御できるのはプラグインのロード順だけではありません。プラグインがどの環境にロードされるか、あるいはどのスコープ(ビルドの各段階)でロードされるかを指定することもできます。やり方は、それぞれのプロパティをプラグインディスクリプタ中に宣言するだけです。
def environments = ['development', 'test', 'myCustomEnv'] def scopes = [excludes:'war']
development-only
plugins to not be packaged for production use.この例では、プラグインは「development」と「test」環境のときだけロードされます。また、warフェイズからは除外設定されているので、WARファイル中にはパッケージされません。こうすることで、development-only
のプラグインは、実運用時にはパッケージされないようにできます。
利用可能なスコープの全てのリストはenum BuildScopeで定義されていますが、以下はその抜粋です:
*test
- when running tests *functional-test
- when running functional tests *run
- for run-app and run-war *war
- when packaging the application as a WAR file *all
- plugin applies to all scopes (default)
test
- テスト実行時functional-test
- ファンクショナルテスト実行時run
- run-appもしくはrun-war時war
- アプリケーションがWARファイルにパッケージ化されたときall
- 全てのスコープに適用されるプラグイン(デフォルト)
いずれのプロパティにも以下のうち1つを設定することができます。
- a string - a sole inclusion
- a list - a list of environments or scopes to include
- a map - for full control, with 'includes' and/or 'excludes' keys that can have string or list values
- a string - 1つ含む
- a list - 含められるべき環境もしくはスコープのリスト
- a map - 全ての制御。キーは'includes'か'excludes'で、バリューは文字列もしくはリスト
例えば、
def environments = "test"
という指定の場合、テスト環境のみでプラグインが含められます。これに対して
def environments = ["development", "test"]
はdevelopment と test環境の両方を含みます。最後に
def environments = [includes: ["development", "test"]]
も同様の意味です。
15.11 アーテファクトAPI
これまでの説明で、Grailsにはアーテファクトという概念があることが理解できたと思います。アーテファクトは特別なクラス型であり、通常のGroovyやJavaクラスとは異なるやり方で処理されます。例えば、プロパティやメソッドを追加することで拡張できます。アーテファクトの例は、ドメインクラスやコントローラです。気づいていなかったかもしれませんが、Grailsはアプリケーションやプラグイン開発者が、アーテファクトのための下位層のインフラストラクチャにアクセスすることを許しています。これが意味するのは、どんなアーテファクトが利用可能であるかを調べたり、あるいはそれらを拡張したりすることができるということです。また、あなた独自のカスタムアーテファクト型を追加することさえも可能です。
15.11.1 使用可能なアーテファクトの検索
searchable
properties and index the appropriate ones. So how does it do it? The answer lies with the grailsApplication
object, and instance of GrailsApplication that's available automatically in controllers and GSPs and can be injected everywhere else.プラグイン開発者からすると、アプリケーションにおいて、どのドメインクラス・コントローラや他のアーテファクトが利用可能かが分かる、ということが重要かもしれません。
例えば、Searchableプラグインは、インデックス化すべきであることを指定するsearchable
プロパティをチェックするために、どんなドメインクラスが存在しているかをまず知る必要があります。では、どんなふうにチェックできるのでしょう? 答えはgrailsApplication
オブジェクトとGrailsApplicationのインスタンスにあります。これらはコントローラとGSP中では自動的に利用可能となり、他の任意の場所で注入しておくことができます。
grailsApplication
object has several important properties and methods for querying artefacts. Probably the most common is the one that gives you all the classes of a particular artefact type:grailsApplication
オブジェクトは、アーテファクトを検索するためのいくつかの重要なプロパティとメソッドを保持しています。
for (cls in grailsApplication.<artefactType>Classes) {
…
}
artefactType
is the property name form of the artefact type. With core Grails you have:この場合、artefactType
は、プロパティ名中でアーテファクト型を指定する形式であり、Grailsコアでは以下が指定できます:
- domain
- controller
- tagLib
- service
- codec
- bootstrap
- urlMappings
例えば、繰り返し処理をすべてのドメインクラスについてしたいならば、以下を使います:
for (cls in grailsApplication.domainClasses) {
…
}
URLマッピングの場合なら以下です:
for (cls in grailsApplication.urlMappingsClasses) {
…
}
Class
:これらのプロパティが返すのはクラス(java.lang.Class)のインスタンスではないことに留意する必要があります。そうではなく、これらはGrailsClassのインスタンスであり、下位のClass
型用のものも含め、以下のような便利なプロパティやメソッドが利用可能です。
shortName
- the class name of the artefact without the package (equivalent ofClass.simpleName
).logicalPropertyName
- the artefact name in property form without the 'type' suffix. SoMyGreatController
becomes 'myGreat'.isAbstract()
- a boolean indicating whether the artefact class is abstract or not.getPropertyValue(name)
- returns the value of the given property, whether it's a static or an instance one. This works best if the property is initialised on declaration, e.g.static transactional = true
.
shortName
- パッケージ部分を除いたアーテファクトのクラス名(Class.simpleName
と等価)logicalPropertyName
- プロパティ中で用いられる名アーテファクトの名前から型接尾辞を除いたもの。MyGreatController
は「myGreat」になる。isAbstract()
- アーテファクトクラスがabstractかどうかを表すブーリアン値getPropertyValue(name)
- 指定したプロパティ値を、staticか非staticかどうかに関わらず返す。もしプロパティが「static transactional = true
」のように初期化されて宣言されていたときにも動作する。
アーテファクトAPIで、クラスを名前で取得したり、指定したクラスがアーテファクトかどうかを判断したりすることができます:
- get<type>Class(String name)
- is<type>Class(Class clazz)
GrailsClass
instance for the given name, e.g. 'MyGreatController'. The second will check whether a class is a particular type of artefact. For example, you can use grailsApplication.isControllerClass(org.example.MyGreatController)
to check whether MyGreatController
is in fact a controller.最初のメソッドは、指定した名前、たとえば「MyGreatController」からGrailsClass
インスタンスを取得します。二番目のメソッドは、クラスが特定のアーテファクトの型かどうかを判断します。例えば、grailsApplication.isControllerClass(org.example.MyGreatController)
とすることで、MyGreatController
がコントローラかどうかをチェックすることができます。
15.11.2 アーテファクト型の追加
ArtefactHandler
implementation and register it in your main plugin class:プラグインでは、どんな実装が利用できるかわかり、自動リロードの過程に組込むことができるような、自分自身のアーテファクトを簡単に提供することができます。そのためにやるべきことは、ArtefactHandler
の実装を生成し、メインのプラグインクラス中に登録しておくことだけです:
class MyGrailsPlugin { def artefacts = [ org.somewhere.MyArtefactHandler ] … }
artefacts
list can contain either handler classes (as above) or instances of handlers.リストartefacts
は、ハンドラクラス(上述)もしくはハンドラの一連のインスタンスを保持することができます。
それでは、アーテファクトハンドラは、どのようなものでしょうか?ここでは単にArtefactHandlerインターフェースを実装するものということにしておきます。利便のため、extendsすればすぐ使えるスケルトン実装ArtefactHandlerAdapterも用意されています。
ハンドラそれ自身に加えて、新しいアーテファクトは、GrailsClassをimplementsする対応するラッパークラスを必要とします。こちらもAbstractInjectableGrailsClassなどのスケルトン実装が利用可能です。これはあなたのアーテファクトを、コントローラやサービスのようにオートワイヤ可能なSpringビーンにしてくれるので特に便利でしょう。
ハンドラとラッパーの動作を理解するのにベストなやり方は、Quartz pluginのコードを読んでみることです:
他の例としては、Shiroプラグインがあり、こちらはrealmアーテファクトを追加します。
15.12 バイナリープラグイン
- Binary plugins can be published as standard JAR files to a Maven repository
- Binary plugins can be declared like any other JAR dependency
- Commercial plugins are more viable since the source isn't published
- IDEs have a better understanding since binary plugins are regular JAR files containing classes
- Mavenリポジトリで通常のJARファイルで配布可能。
- バイナリプラグインは他のJARと同じように依存管理が行える。
- ソースコードを公開しない商用プラグインが可能
- 通常のJARになることによって、IDE等の環境で扱いやすくなる
パッケージング Packaging
--binary
flag:--binary
フラグを使用します
grails package-plugin --binary
- Grails artifact classes such as controllers, domain classes and so on
- I18n Message bundles
- GSP Views, layouts and templates
- コントローラ、ドメイン等のGrailsのアーテファクトクラス
- I18nメッセージファイル
- GSPビュー、レイアウト、テンプレート
def packaging = "binary"
バイナリプラグイン使用方法 Using Binary Plugins
target
directory of the plugin, for example target/foo-plugin-0.1.jar
. There are two ways to incorporate a binary plugin into an application.targrt
ディレクトリに生成されます。例としてtarget/foo-plugin-0.1.jar
。 バイナリプラグインを使用するには2つの方法があります。
lib
directory. The other is to publish the plugin JAR to a compatible Maven repository and declare it as a dependency in grails-app/conf/BuildConfig.groovy
:lib
ディレクトリに配置。もう一つの方法は、Mavenリポジトリに配備して、grails-app/conf/BuildConfig.groovy
に依存定義を行います。
dependencies {
compile "mycompany:myplugin:0.1"
}
Since binary plugins are packaged as JAR files, they are declared as dependencies in theバイナリプラグインは依存定義をdependencies
block, not in theplugins
block as you may be naturally inclined to do. Theplugins
block is used for declaring traditional source plugins packaged as zip filesdependencies
ブロックに記述します。plugins
ブロックは今までのソースコードがzipされたプラグインで使用します。
16 GrailsとSpring
16.1 Grailsの土台
- Basic controller logic - Grails subclasses Spring's DispatcherServlet and uses it to delegate to Grails controllers
- 基本的なコントローラのロジック - GrailsのサーブレットはSpringのDispatcherServletのサブクラスであり、それを用いてGrailsのコントローラにディスパッチを行います
- Data Binding and Validation - Grails' validation and data binding capabilities are built on those provided by Spring
- データバインディングとバリデーション - Grailsのバリデーションとデータバインディングの機能は、Springで提供されているものを用いています
- Runtime configuration - Grails' entire runtime convention based system is wired together by a Spring ApplicationContext
- ランタイム設定 - Grailsランタイム全体の規約に基づくシステムはSpringのApplicationContextと結びついています
- Transactions - Grails uses Spring's transaction management in GORM
- トランザクション - GrailsはSpringのトランザクション管理をGORMで利用しています
The Grails ApplicationContext
Grailsアプリケーションコンテキスト
ApplicationContext
instance is constructed. The basics of it are as follows.
ApplicationContext
インスタンスが組み立てられるのか理解したい、と熱心に望んでいます。
基本的には次のようになります:- Grails constructs a parent
ApplicationContext
from theweb-app/WEB-INF/applicationContext.xml
file. ThisApplicationContext
configures the GrailsApplication instance and the GrailsPluginManager.
- Grailsが
web-app/WEB-INF/applicationContext.xml
ファイルから親となるApplicationContext
を組み立てます。このApplicationContext
はGrailsApplicationインスタンスとGrailsPluginManagerを設定します。
- Using this
ApplicationContext
as a parent Grails' analyses the conventions with theGrailsApplication
instance and constructs a childApplicationContext
that is used as the rootApplicationContext
of the web application
- この親となる
ApplicationContext
を用いて、GrailsApplication
インスタンスと共にGrailsの規約を解析し、Webアプリケーションのルートとして利用される子ApplicationContext
を組み立てます。
Configured Spring Beans
構成されたSpringビーン
ApplicationContext
. For a reference as to which beans are configured, refer to the reference guide which describes each of the Grails plugins and which beans they configure.
ApplicationContext
に登録されているSpringビーンを構成することができます。
構成されるビーンの詳細については各プラグインのリファレンスガイドを参照してください。
16.2 追加ビーンを定義する
Using the Spring Bean DSL
SpringビーンDSLの使用
grails-app/conf/spring/resources.groovy
which uses the Grails Spring DSL. Beans are defined inside a beans
property (a Closure):
grails-app/conf/spring/resources.groovy
に設定することで、簡単に新しいビーンが登録(または上書き)できます。
ビーンはbeans
プロパティ(クロージャ)の内部に設定します。beans = { // beans here }
import my.company.MyBeanImplbeans = { myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" } }
BootStrap.groovy
and integration tests) by declaring a public field whose name is your bean's name (in this case myBean
):
myBean
)で宣言することで、Grailsのアーティファクトや、他の依存性の注入がサポートされているクラス(例えば、BootStrap.groovy
やインテグレーションテスト)にビーンが自動注入されます。class ExampleController {def myBean … }
import grails.util.Environment import my.company.mock.MockImpl import my.company.MyBeanImplbeans = { switch(Environment.current) { case Environment.PRODUCTION: myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" } break
case Environment.DEVELOPMENT: myBean(MockImpl) { someProperty = 42 otherProperty = "blue" } break } }
GrailsApplication
object can be accessed with the application
variable and can be used to access the Grails configuration (amongst other things):
GrailsApplication
オブジェクトはapplication
変数で参照でき、Grailsの設定などにアクセスできます。import grails.util.Environment import my.company.mock.MockImpl import my.company.MyBeanImplbeans = { if (application.config.my.company.mockService) { myBean(MockImpl) { someProperty = 42 otherProperty = "blue" } } else { myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" } } }
If you define a bean in resources.groovy
with the same name as one previously registered by Grails or an installed plugin, your bean will replace the previous registration. This is a convenient way to customize behavior without resorting to editing plugin code or other approaches that would affect maintainability.
もし、Grailsやインストールしたプラグインによって登録された名前のビーンをresources.groovy
に定義した場合は、既存で登録されいているビーンが自分で登録したビーンに置き換えられます。
これは、既存の振る舞いをカスタマイズする便利な方法です。
既存のプラグインのコードを変更することなく、またメンテンナンスに影響を与えることもありません。
Using XML
XMLの使用
grails-app/conf/spring/resources.xml
. In earlier versions of Grails this file was automatically generated for you by the run-app
script, but the DSL in resources.groovy
is the preferred approach now so it isn't automatically generated now. But it is still supported - you just need to create it yourself.
grails-app/conf/spring/resources.xml
を使用して定義することもできます。
このXMLファイルは、以前のGrailsのバージョンではrun-app
を実行したタイミングで自動的に生成されていました。
しかし、現在はresources.groovy
でDSLを使用した方法が推奨のため、このXMLファイルが自動的に生成されることはありません。
自動的に生成はされませんが、まだサポートはされています。もし使用したい場合は、手動でこのファイルを作成します。myBean
bean that we configured using the DSL would be configured with this syntax in the XML file:
myBean
は、XMLファイルでは以下のように定義できます。<bean id="myBean" class="my.company.MyBeanImpl"> <property name="someProperty" value="42" /> <property name="otherProperty" value="blue" /> </bean>
class ExampleController {def myBean }
Referencing Existing Beans
既存ビーンの参照
resources.groovy
or resources.xml
can reference other beans by convention. For example if you had a BookService
class its Spring bean name would be bookService
, so your bean would reference it like this in the DSL:
resources.groovy
、またはresources.xml
に定義したビーンは、規約によって登録された他のビーンを参照できます。例えば、BookService
クラスがあったとすると、Springのビーンの名前はbookService
になります。
これを、DSL内で参照するには以下のようにします。beans = { myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" bookService = ref("bookService") } }
<bean id="myBean" class="my.company.MyBeanImpl"> <property name="someProperty" value="42" /> <property name="otherProperty" value="blue" /> <property name="bookService" ref="bookService" /> </bean>
package my.companyclass MyBeanImpl { Integer someProperty String otherProperty BookService bookService // or just "def bookService" }
package my.company;class MyBeanImpl {
private BookService bookService; private Integer someProperty; private String otherProperty;
public void setBookService(BookService theBookService) { this.bookService = theBookService; }
public void setSomeProperty(Integer someProperty) { this.someProperty = someProperty; }
public void setOtherProperty(String otherProperty) { this.otherProperty = otherProperty; } }
ref
(in XML or the DSL) is very powerful since it configures a runtime reference, so the referenced bean doesn't have to exist yet. As long as it's in place when the final application context configuration occurs, everything will be resolved correctly.
ref
は実行時の参照を設定するため非常に強力です。これは定義時に参照するビーンが存在している必要がありません。最終的にアプリケーションコンテキストの設定が完了した時点で、そのビーンが存在していれば正しく参照が解決されます。16.3 ビーンDSLでSpringランタイム
The BeanBuilder class
BeanBuilderクラス
import org.apache.commons.dbcp.BasicDataSource import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean import org.springframework.context.ApplicationContext import grails.spring.BeanBuilderdef bb = new BeanBuilder()
bb.beans {
dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:grailsDB" username = "sa" password = "" }
sessionFactory(ConfigurableLocalSessionFactoryBean) { dataSource = ref('dataSource') hibernateProperties = ["hibernate.hbm2ddl.auto": "create-drop", "hibernate.show_sql": "true"] } }
ApplicationContext appContext = bb.createApplicationContext()
Within plugins and the grails-app/conf/spring/resources.groovy file you don't need to create a new instance ofBeanBuilder
. Instead the DSL is implicitly available inside thedoWithSpring
andbeans
blocks respectively.
pluginsとgrails-app/conf/spring/resources.groovyファイルではBeanBuilder
のインスタンスを新たに作成する必要はありません。 これらは、暗黙的にぞれぞれdoWithSpring
、beans
ブロック内でDSLが使用可能です。
BeanBuilder
class.
BeanBuilder
クラスを使用して、データソースとHibernateの設定を行なっています。dataSource
and sessionFactory
calls) maps to the name of the bean in Spring. The first argument to the method is the bean's class, whilst the last argument is a block. Within the body of the block you can set properties on the bean using standard Groovy syntax.
dataSource
とsessionFactory
)、Springのビーン名にマッピングされます。
そして、1つ目のメソッドの引数にはビーンのクラスを指定し、2つ目の引数にはブロックを指定します。
このブロックの内部では、一般的なGroovyのシンタックスを使用してBeanのプロパティを設定することが可能です。sessionFactory
bean resolves the dataSource
reference.
sessionFactory
ビーンで、dataSource
への参照を解決しています。sessionFactory(ConfigurableLocalSessionFactoryBean) { bean -> // Autowiring behaviour. The other option is 'byType'. [autowire] bean.autowire = 'byName' // Sets the initialisation method to 'init'. [init-method] bean.initMethod = 'init' // Sets the destruction method to 'destroy'. [destroy-method] bean.destroyMethod = 'destroy' // Sets the scope of the bean. [scope] bean.scope = 'request' dataSource = ref('dataSource') hibernateProperties = ["hibernate.hbm2ddl.auto": "create-drop", "hibernate.show_sql": "true"] }
Using BeanBuilder with Spring MVC
Spring MVCでBeanBuilderを使用する
grails-spring-<version>.jar
file in your classpath to use BeanBuilder in a regular Spring MVC application. Then add the following <context-param>
values to your /WEB-INF/web.xml
file:
grails-spring-<version>.jar
を追加します。
そしてWEB-INF/web.xml
ファイルに<context-param>
の値を追加します。<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.groovy</param-value> </context-param><context-param> <param-name>contextClass</param-name> <param-value> org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext </param-value> </context-param>
/WEB-INF/applicationContext.groovy
file that does the rest:
/WEB-INF/applicationContext.groovy
ファイルを作成するだけです。import org.apache.commons.dbcp.BasicDataSourcebeans { dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:grailsDB" username = "sa" password = "" } }
Loading Bean Definitions from the File System
ファイルシステムからBean定義を読み込む
BeanBuilder
class to load external Groovy scripts that define beans using the same path matching syntax defined here. For example:
BeanBuilder
クラスを使用して外部のGroovyスクリプトを読み込むには、パスマッチングのシンタックスを使用します。以下に例を示します。def bb = new BeanBuilder() bb.loadBeans("classpath:*SpringBeans.groovy")def applicationContext = bb.createApplicationContext()
BeanBuilder
loads all Groovy files on the classpath ending with SpringBeans.groovy
and parses them into bean definitions. An example script can be seen below:
BeanBuilder
はクラスパス内のSpringBeans.groovy
という名前で終わる、全てのGroovyファイルをビーンの定義として読み込みます。
スクリプトの中身は以下のように定義できます。import org.apache.commons.dbcp.BasicDataSource import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBeanbeans {
dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:grailsDB" username = "sa" password = "" }
sessionFactory(ConfigurableLocalSessionFactoryBean) { dataSource = dataSource hibernateProperties = ["hibernate.hbm2ddl.auto": "create-drop", "hibernate.show_sql": "true"] } }
Adding Variables to the Binding (Context)
バインディング(コンテキスト)に変数を追加する
Binding
:
Binding
インスタンスを作成してバインドが行えます。def binding = new Binding() binding.maxSize = 10000 binding.productGroup = 'finance'def bb = new BeanBuilder() bb.binding = binding bb.loadBeans("classpath:*SpringBeans.groovy")
def ctx = bb.createApplicationContext()
maxSize
and productGroup
properties in your DSL files.
maxSize
、productGroup
プロパティにアクセスすることが可能になります。
16.4 ビーンビルダーDSLの解説
Using Constructor Arguments
コンストラクタ引数の使い方
bb.beans {
exampleBean(MyExampleBean, "firstArgument", 2) {
someProperty = [1, 2, 3]
}
}
MyExampleBean
with a constructor that looks like this:
MyExampleBean
のコンストラクタに対応付けされます。MyExampleBean(String foo, int bar) { … }
Configuring the BeanDefinition (Using factory methods)
ビーン定義の設定 (ファクトリメソッドの利用)
bb.beans { exampleBean(MyExampleBean) { bean -> bean.factoryMethod = "getInstance" bean.singleton = false someProperty = [1, 2, 3] } }
bb.beans {
def example = exampleBean(MyExampleBean) {
someProperty = [1, 2, 3]
}
example.factoryMethod = "getInstance"
}
Using Factory beans
ファクトリビーンの利用
bb.beans {myFactory(ExampleFactoryBean) { someProperty = [1, 2, 3] }
myBean(myFactory) { name = "blah" } }
bb.beans {myFactory(ExampleFactoryBean) { someProperty = [1, 2, 3] }
myBean(myFactory: "getInstance") { name = "blah" } }
getInstance
method on the ExampleFactoryBean
bean will be called to create the myBean
bean.
ExampleFactoryBean
ビーン上のgetInstance
メソッドがmyBean
ビーンの生成時に呼び出されます。Creating Bean References at Runtime
ビーンへの参照を実行時に生成する
def beanName = "example" bb.beans { "${beanName}Bean"(MyExampleBean) { someProperty = [1, 2, 3] } }
beanName
variable defined earlier is used when invoking a bean defining method. The example has a hard-coded value but would work just as well with a name that is generated programmatically based on configuration, system properties, etc.
beanName
変数を用いてビーン定義メソッドを呼び出しています。
この例では値をハードコードしていますが、設定やシステムプロパティ等に基づいて生成された名前でも同様に動作します。ref
method:
ref
メソッドを用いて他のビーンから名前で参照する必要が生じることがあります。def beanName = "example" bb.beans {"${beanName}Bean"(MyExampleBean) { someProperty = [1, 2, 3] }
anotherBean(AnotherBean) { example = ref("${beanName}Bean") } }
AnotherBean
is set using a runtime reference to the exampleBean
. The ref
method can also be used to refer to beans from a parent ApplicationContext
that is provided in the constructor of the BeanBuilder
:
exampleBean
への実行時参照を用いてAnotherBean
のプロパティに設定しています。
BeanBuilder
のコンストラクタで提供される親ApplicationContext
からビーンを参照するためにも、ref
メソッドを使うことができます。ApplicationContext parent = ...// der bb = new BeanBuilder(parent) bb.beans { anotherBean(AnotherBean) { example = ref("${beanName}Bean", true) } }
true
specifies that the reference will look for the bean in the parent context.
ref
メソッドの第2引数にtrue
を渡すことで、親となるコンテキストからビーンを探すことを指定しています。Using Anonymous (Inner) Beans
匿名(内部)ビーンを使う
bb.beans {marge(Person) { name = "Marge" husband = { Person p -> name = "Homer" age = 45 props = [overweight: true, height: "1.8m"] } children = [bart, lisa] }
bart(Person) { name = "Bart" age = 11 }
lisa(Person) { name = "Lisa" age = 9 } }
marge
bean's husband property to a block that creates an inner bean reference. Alternatively if you have a factory bean you can omit the type and just use the specified bean definition instead to setup the factory:
merge
ビーンのhusband
プロパティに、内部ビーンの参照を作成したブロックを渡しています。
ファクトリを持つビーンは型を省略でき、ファクトリをセットアップする代わりに指定されたビーンの定義を利用するだけで済みます。bb.beans {personFactory(PersonFactory)
marge(Person) { name = "Marge" husband = { bean -> bean.factoryBean = "personFactory" bean.factoryMethod = "newInstance" name = "Homer" age = 45 props = [overweight: true, height: "1.8m"] } children = [bart, lisa] } }
Abstract Beans and Parent Bean Definitions
抽象ビーンと親ビーンの定義
Class
parameter:
Class
を渡さずに定義します。class HolyGrailQuest {
def start() { println "lets begin" }
}
class KnightOfTheRoundTable {String name String leader HolyGrailQuest quest
KnightOfTheRoundTable(String name) { this.name = name }
def embarkOnQuest() { quest.start() } }
import grails.spring.BeanBuilderdef bb = new BeanBuilder() bb.beans { abstractBean { leader = "Lancelot" } … }
leader
property with the value of "Lancelot"
. To use the abstract bean set it as the parent of the child bean:
"Lancelot"
が入っているleader
プロパティを持つ抽象ビーンを定義しています。
子ビーンの親として抽象ビーンを使うには、次のように設定します。bb.beans { … quest(HolyGrailQuest)knights(KnightOfTheRoundTable, "Camelot") { bean -> bean.parent = abstractBean quest = ref('quest') } }
When using a parent bean you must set the parent property of the bean before setting any other properties on the bean!
親ビーンを利用するときは、ビーン上の他のプロパティを設定する前に、ビーンのparent
プロパティへ設定する必要があります。
Class
specified you can do it this way:
Class
を明示して抽象ビーンを利用したい場合は、次に示す方法で可能です。import grails.spring.BeanBuilderdef bb = new BeanBuilder() bb.beans {
abstractBean(KnightOfTheRoundTable) { bean -> bean.'abstract' = true leader = "Lancelot" }
quest(HolyGrailQuest)
knights("Camelot") { bean -> bean.parent = abstractBean quest = quest } }
KnightOfTheRoundTable
and use the bean argument to set it to abstract. Later we define a knights bean that has no Class
defined, but inherits the Class
from the parent bean.
abstract
プロパティを利用してKnightOfTheRoundTable
型の抽象ビーンを作成しています。
その後、Class
の指定のないknights
ビーンを定義していますが、Class
は親ビーンから継承されます。Using Spring Namespaces
Springの名前空間を使う
BeanBuilder
でSpringの名前空間を使うことができます。xmlns context:"http://www.springframework.org/schema/context"
context.'component-scan'('base-package': "my.company.domain")
xmlns jee:"http://www.springframework.org/schema/jee"jee.'jndi-lookup'(id: "dataSource", 'jndi-name': "java:comp/env/myDataSource")
dataSource
by performing a JNDI lookup on the given JNDI name. With Spring namespaces you also get full access to all of the powerful AOP support in Spring from BeanBuilder. For example given these two classes:
dataSource
という識別子で、与えられたJNDI名でJNDIを解決するSpringビーンを作成します。
また、Spring名前空間によってBeanBuilder
から強力なSpringのAOPサポートにフルアクセスできます。
2つのクラスを使って例を示します。class Person {int age String name
void birthday() { ++age; } }
class BirthdayCardSender {List peopleSentCards = []
void onBirthday(Person person) { peopleSentCards << person } }
birthday()
method is called:
birthday()
メソッドの呼び出しを検出するポイントカットを使用して、アスペクトを次のように定義できます。xmlns aop:"http://www.springframework.org/schema/aop"fred(Person) { name = "Fred" age = 45 }
birthdayCardSenderAspect(BirthdayCardSender)
aop { config("proxy-target-class": true) { aspect(id: "sendBirthdayCard", ref: "birthdayCardSenderAspect") { after method: "onBirthday", pointcut: "execution(void ..Person.birthday()) and this(person)" } } }
16.5 プロパティプレースホルダ設定
grails-app/conf/spring/resources.xml
and grails-app/conf/spring/resources.groovy
. For example given the following entries in grails-app/conf/Config.groovy
(or an externalized config):
grails-app/conf/spring/resources.xml
とgrails-app/conf/spring/resources.groovy
のSpringの設定ファイル内で使用できます。
例えば、grails-app/conf/Config.groovy
(または外部設定)で以下の設定があるとします。database.driver="com.mysql.jdbc.Driver" database.dbname="mysql:mydb"
resources.xml
as follows using the familiar ${..} syntax:
resources.xml
内では、使い慣れた${..}のシンタックスを使用してプレースホルダを指定できます。<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${database.driver}</value> </property> <property name="url"> <value>jdbc:${database.dbname}</value> </property> </bean>
resources.groovy
you need to use single quotes:
resources.groovy
内でプレースホルダを指定するには、シングルクォートを使用する必要があります。dataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) { driverClassName = '${database.driver}' url = 'jdbc:${database.dbname}' }
resources.groovy
is to access properties through the grailsApplication
variable:
resources.groovy
ではgrailsApplication
にアクセスすることが可能です。dataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) {
driverClassName = grailsApplication.config.database.driver
url = "jdbc:${grailsApplication.config.database.dbname}"
}
16.6 プロパティオーバーライド設定
beans
block with the names of beans and their values:
beans
ブロックにビーンの名前と値を定義して行います。beans {
bookService {
webServiceURL = "http://www.amazon.com"
}
}
[bean name].[property name] = [value]
beans.bookService.webServiceURL=http://www.amazon.com
17 GrailsとHibernate
17.1 Hibernate XMLマッピングの使用
hibernate.cfg.xml
file in your project's grails-app/conf/hibernate
directory, either manually or with the create-hibernate-cfg-xml command, that contains the following:
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" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Example mapping file inclusion --> <mapping resource="org.example.Book.hbm.xml"/> … </session-factory> </hibernate-configuration>
grails-app/conf/hibernate
directory. To find out how to map domain classes with XML, check out the Hibernate manual.
grails-app/conf/hibernate
ディレクトリに格納します。
XMLを使用して、どうのようにドメインクラスをマッピングするかはHibernateのマニュアルを確認してください。hibernate.cfg.xml
file doesn't suit you, you can change it by specifying an alternative location in grails-app/conf/DataSource.groovy
:
hibernate.cfg.xml
ファイルのデフォルトの格納場所を変更したい場合は、grails-app/conf/DataSource.groovy
に別の場所を指定することで変更できます。hibernate {
config.location = "file:/path/to/my/hibernate.cfg.xml"
}
hibernate { config.location = ["file:/path/to/one/hibernate.cfg.xml", "file:/path/to/two/hibernate.cfg.xml"] }
grails-app/conf/hibernate
and either put the Java files in src/java
or the classes in the project's lib
directory if the domain model is packaged as a JAR. You still need the hibernate.cfg.xml
though!
grails-app/conf/hibernate
に格納し、Javaファイルはsrc/java
に格納するか、ドメインモデルがJARファイルでパッケージングされている場合は、lib
ディレクトリにそのクラスのJARファイルを格納します。
その場合でもhibernate.cfg.xml
は必要です。
17.2 Hibernateアノテーションでのマッピング
src/java
and use the annotations defined as part of the EJB 3.0 spec (for more info on this see the Hibernate Annotations Docs):
src/java
に新たなクラスを作成し、EJB 3.0の仕様として定義されているアノテーションを使用します(より詳細な情報はHibernateのアノテーションに関するドキュメントを参照してください)。package com.books;import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;
@Entity public class Book { private Long id; private String title; private String description; private Date date;
@Id @GeneratedValue public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; } }
sessionFactory
by adding relevant entries to the grails-app/conf/hibernate/hibernate.cfg.xml
file as follows:
grails-app/conf/hibernate/hibernate.cfg.xml
ファイルに関連エントリを以下のように追加することで、HibernateのsessionFactory
にクラスを登録します。<!DOCTYPE hibernate-configuration SYSTEM "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <mapping package="com.books" /> <mapping class="com.books.Book" /> </session-factory> </hibernate-configuration>
hibernate.cfg.xml
file.
hibernate.cfg.xml
ファイルの詳細は、前のセクションを参照してください。17.3 制約の追加
src/java
directory. The script must be in a directory that matches the package of the corresponding domain class and its name must have a Constraints suffix. For example, if you had a domain class org.example.Book
, then you would create the script src/java/org/example/BookConstraints.groovy
.
src/java
ディレクトリ内の、別個のスクリプトを通じて制約を定義します。
このスクリプトは、対応するドメインクラスのパッケージと同じディレクトリ内に格納し、ファイル名のサフィックスは Constraints でなければなりません。
たとえば、org.example.Book
というドメインクラスの場合は、src/java/org/example/BookConstraints.groovy
というスクリプトを作成します。constraints
block to the script:
constraints
ブロックを追加してください。constraints = { title blank: false author blank: false }
18 スカッフォルド
- The necessary views
- Controller actions for create/read/update/delete (CRUD) operations
- 必要なビュー
- 作成/参照/更新/削除(CRUD)処理のコントローラアクション
As of Grails 2.3, the scaffolding feature has been moved to a plugin. By default this is configured for installation in new applications, but if you are upgrading from a previous version of Grails you will need to add the following configuration to your BuildConfig.groovy
file:
plugins {
…
compile ">>
…
}
Version 1.0.0 of the plugin provides the same scaffolding seen in Grails 2.2.x and below. Version 2.0.x of the scaffolding plugin includes different scaffolding templates that are aligned with the new REST APIs introcued in Grails 2.3 and above.
Dynamic Scaffolding
動的スカッフォルド
scaffold
property. Set the scaffold
property in the controller to true
for the Book
domain class:
scaffold
プロパティを設定することです。以下はBook
ドメインクラスのコントローラにてscaffold
プロパティをtrue
に設定しています。class BookController { static scaffold = true }
BookController
follows the same naming convention as the Book
domain class. To scaffold a specific domain class we could reference the class directly in the scaffold property:
BookController
がBook
ドメインクラスと同じ命名規則に従っているためです。特定のドメインクラスに対してスカッフォルドを利用する場合、以下の様にscaffold
プロパティからそのクラスを直接参照できます。class SomeController {
static scaffold = Author
}
- index
- show
- edit
- delete
- create
- save
- update
- index
- show
- edit
- delete
- create
- save
- update
http://localhost:8080/app/book
in a browser.
http://localhost:8080/app/book
を開いてください。scaffold
argument.
scaffold
の引数に設定してください。class BookController {static scaffold = Book
def changeAuthor() { def b = Book.get(params.id) b.author = Author.get(params["author.id"]) b.save()
// redirect to a scaffolded action redirect(action:show) } }
class BookController {static scaffold = Book
// overrides scaffolded action to return both authors and books def index() { [bookInstanceList: Book.list(), bookInstanceTotal: Book.count(), authorInstanceList: Author.list()] }
def show() { def book = Book.get(params.id) log.error(book) [bookInstance : book] } }
By default, the size of text areas in scaffolded views is defined in the CSS, so adding 'rows' and 'cols' attributes will have no effect.Also, the standard scaffold views expect model variables of the form
<propertyName>InstanceList
for collections and<propertyName>Instance
for single instances. It's tempting to use properties like 'books' and 'book', but those won't work.
デフォルトではスカッフォルドで生成されるビューのテキストエリアのサイズはCSSで定義されているため、'rows'や'cols'属性追加は無効です。 また標準的なスカッフォルドのビューはコレクションには<propertyName>InstanceList
書式の変数モデルを期待し、シングルインスタンスには<propertyName>Instance
を期待します。'books'や'book'といったプロパティを使ってみたくなるかもしれませんが、うまく機能しません。
Customizing the Generated Views
生成されるビューのカスタマイズ
def constraints = { title() releaseDate() }
inList
constraint:
inList
制約を使うとテキスト入力の代わりにリストを生成することができます。def constraints = { title() category(inList: ["Fiction", "Non-fiction", "Biography"]) releaseDate() }
range
constraint on a number:
range
制約を使用することもできます。def constraints = { age(range:18..65) }
def constraints = { name(size:0..30) }
Static Scaffolding
静的スカッフォルド
grails generate-controller Book
grails generate-views Book
grails generate-all Book
grails generate-all com.bookstore.Book
Customizing the Scaffolding templates
スカッフォルドテンプレートのカスタマイズ
19 デプロイ
"grails run-app"
grails prod run-app
removes the per-request overhead and lets you fine tune how frequently the regular check takes place.grails prod run-app
コマンドを利用することで上記処理を実施しないようにする事ができ、更新検出のオーバーヘッドをなくす事が出来ます。true
disables this regular check completely, while the property "recompile.frequency" controls the frequency. This latter property should be set to the number of seconds you want between each check. The default is currently 3.disable.auto.recompile=true
を指定する事で再コンパイルを無効にする事ができます。
また、recompile.frequency
という起動オプションで構文のチェック頻度を指定できます。チェック頻度は数字(秒)で指定します。なお、本値のデフォルト値は3秒です。"grails run-war"
grails run-app
ではTomcatサーバがソースコードを読み込んで動作するのに対して、grails run-war
ではWARファイルを利用して動作します。
このコマンドによる起動では自動再読み込みが実施されず、WARファイルの面倒なデプロイをする必要もなく、高いパフォーマンスでの実行が可能です。WARファイル
grails war
grails war /opt/java/tomcat-5.5.24/foobar.war
grails-app/conf/BuildConfig.groovy
that changes the default location and filename:grails-app/conf/BuildConfig.groovy
に以下の行を追加する事でデフォルトのファイル名称及びファイル出力先を指定する事が出来ます。grails.project.war.file = "foobar-prod.war"
grails.war.dependencies
in BuildConfig.groovy to either lists of Ant include patterns or closures containing AntBuilder syntax. Closures are invoked from within an Ant "copy" step, so only elements like "fileset" can be included, whereas each item in a pattern list is included. Any closure or pattern assigned to the latter property will be included in addition to grails.war.dependencies
.grails.war.dependencies
プロパティにAntでインクルードするパターンのリストを設定するか、またはAntBuilder構文で記述したクロージャを設定することで、明示的にWARファイルに含めるライブラリを指定することができます。クロージャはAntの"copy"の処理の中から実行され、インクルードするパターンのリストを指定する"fileset"のみを含むことができます。なお、複数のクロージャ、パターンが指定された場合には末尾に指定されたものが有効化の対象となります。grails.war.dependencies
を指定する場合、Grailsの動作に必要なライブラリ群がない場合にはアプリケーションの起動に失敗するので注意して下さい。
以下にGrailsに最低限必要なライブラリ群を含める場合の記述例について示します。def deps = [ "hibernate3.jar", "groovy-all-*.jar", "standard-${servletVersion}.jar", "jstl-${servletVersion}.jar", "oscache-*.jar", "commons-logging-*.jar", "sitemesh-*.jar", "spring-*.jar", "log4j-*.jar", "ognl-*.jar", "commons-*.jar", "xstream-1.2.1.jar", "xpp3_min-1.1.3.4.O.jar" ]grails.war.dependencies = { fileset(dir: "libs") { for (pattern in deps) { include(name: pattern) } } }
DEFAULT_DEPS
and DEFAULT_J5_DEPS
variables.Grails2.2.0ではdependencies.txtが無くなっています。
JIRAに記載の通り、War.groovyには「DEFAULT_DEPS」及び「DEFAULT_J5_DEPS」の値が存在しません。本家英語ドキュメントの更新が行われていないため、上記内容に該当する箇所は未翻訳としております。
grails.war.copyToWebApp
and grails.war.resources
. The first of these lets you customise what files are included in the WAR file from the "web-app" directory. The second lets you do any extra processing you want before the WAR file is finally created.grails.war.copyToWebApp
、grails.war.resources
のプロパティに関する説明が残っています。grails.war.copyToWebApp
ではWARファイル作成時に "web-app" ディレクトリ配下のどのファイルを含めるかを指定する事が出来ます。grails.war.resources
ではWARファイル作成前に実施したい追加処理を記述する事が出来ます。// This closure is passed the command line arguments used to start the // war process.grails.war.copyToWebApp = { args -> fileset(dir:"web-app") { include(name: "js/**") include(name: "css/**") include(name: "WEB-INF/**") } }
// This closure is passed the location of the staging directory that // is zipped up to make the WAR file, and the command line arguments. // Here we override the standard web.xml with our own. grails.war.resources = { stagingDir, args -> copy(file: "grails-app/conf/custom-web.xml", tofile: "${stagingDir}/WEB-INF/web.xml") }
// このクロージャにはWARファイル作成時のコマンドライン引数が渡されます。 grails.war.copyToWebApp = { args -> fileset(dir:"web-app") { include(name: "js/**") include(name: "css/**") include(name: "WEB-INF/**") } }// このクロージャにはWARファイルがZIP圧縮されるステージング環境のパスとコマンドライン引数が渡されます。 // 本例では標準のweb.xmlをあなたの作成したファイルで上書きします。 grails.war.resources = { stagingDir, args -> copy(file: "grails-app/conf/custom-web.xml", tofile: "${stagingDir}/WEB-INF/web.xml") }
アプリケーションサーバ
20 Grailsに貢献する
20.1 JIRAで課題を報告する(バグ報告)
grails bug-report
command).grails bug-report
コマンドを使ってアプリケーションをパッケージングできます。)課題をレビューする
20.2 ソースからビルドしてテストを実行する
- A JDK (1.6 or above)
- A git client
- JDK (1.6以降)
- gitクライアント
git clone http://github.com/grails/grails-core.git
Grails一式を作成する
GRAILS_HOME
installation. But, it's very simple to turn it into one. Just run this from the root directory of the project:GRAILS_HOME
とはあまり似ていないことに気づくでしょう。
しかし、これを標準的なものに変換するのはとても簡単です。
プロジェクトのルートディレクトリで以下のコマンドを実行します:./gradlew install
GRAILS_HOME
installation. Note that this target skips the extensive collection of Grails test classes, which can take some time to complete.GRAILS_HOME
の一式がビルドされます。
このコマンドでは、完了に時間がかかるGrailsの大量のテストクラスはスキップされることに注意してください。GRAILS_HOME
environment variable to the checkout directory and add the "bin" directory to your path. When you next type run the grails
command, you'll be using the version you just built.GRAILS_HOME
環境変数を今回チェックアウトしたディレクトリにセットし、「bin」ディレクトリにパスを通してください。
これで次にgrails
コマンドを実行したときには、自分でビルドしたバージョンが使われるようになります。テストスイートを実行する
./gradlew test
MappingDslTests
simply execute the following command:MappingDslTests
というテストケースを実行するには、単純に以下のコマンドを実行します:./gradlew -Dtest.single=MappingDslTest :grails-test-suite-persistence:test
IntelliJ IDEAで開発する
./gradlew idea
STS/Eclipseで開発する
./gradlew cleanEclipse eclipse
grails-scripts/.classpath
を編集して、<classpathentry kind="src" path="../scripts"/>
の行を削除します。
- Add the springloaded-core JAR file in $GRAILS_HOME/lib/com.springsource.springloaded/springloaded-core/jars to grails-core's classpath.
- Remove "src/test/groovy" from grails-plugin-testing's source path GRECLIPSE-1067
- Add the jsp-api JAR file in $GRAILS_HOME/lib/javax.servlet.jsp/jsp-api/jars to the classpath of grails-web
- Fix the source path of grails-scripts. Add linked source folder linking to "../scripts". If you get build errors in grails-scripts, do "../gradlew cleanEclipse eclipse" in that directory and edit the .classpath file again (remove the line "<classpathentry kind="src" path="../scripts"/>"). Remove possible empty "scripts" directory under grails-scripts if you are not able to add the linked folder.
- Do a clean build for the whole workspace.
- To use Eclipse GIT scm team provider: Select all projects (except "Servers") in the navigation and right click -> Team -> Share project (not "Share projects"). Choose "Git". Then check "Use or create repository in parent folder of project" and click "Finish".
- Get the recommended code style settings from the mailing list thread (final style not decided yet, currently profile.xml). Import the code style xml file to STS in Window->Preferences->Java->Code Style->Formatter->Import . Grails code uses spaces instead of tabs for indenting.
$GRAILS_HOME/lib/com.springsource.springloaded/springloaded-core/jars
にあるspringloaded-coreのJARファイルをgrails-coreのクラスパスに追加します。- grails-plugin-testingのソースパスから
src/test/groovy
を削除します(GRECLIPSE-1067)。 $GRAILS_HOME/lib/javax.servlet.jsp/jsp-api/jars
にあるjsp-apiのJARファイルをgrails-webのクラスパスに追加します。- grails-scriptsのソースパスを修正します。
../scripts
にリンクされたソースの「linked folder」を追加します。もしgrails-scriptsでビルドエラーが出るようなら、grails-scriptsディレクトリで../gradlew cleanEclipse eclipse
を実行し、.classpath
ファイルを再度編集します(<classpathentry kind="src" path="../scripts"/>
という行を削除します)。「linked folder」を追加できない場合、grails-scriptsにある(おそらく空である)scripts
ディレクトリを削除します。 - ワークスペース全体に対しクリーンビルドを実行します。
- 「Eclipse GIT scm team provider」を利用する場合は、ナビゲーションビューで「Servers」以外のすべてのプロジェクトを選択し、右クリックから「Team -> Share project」(複数形ではありませんが)を実行します。「Git」を選び、「Use or create repository in parent folder of project」にチェックを入れ、「Finish」をクリックします。
- 推奨されるコードスタイルの設定はメーリングリストのスレッドから入手してください。(最終的なスタイルはまだ確定されていません。現状版はprofile.xmlです。)メニューの「Window -> Preferences -> Java -> Code Style -> Formatter -> Import」から、コードスタイルのXMLファイルをSTSにインポートします。Grailsコードでは、インデントにはタブではなくスペースを使用します。
GrailsやGrailsアプリケーションをデバッグする
grails -debug <command>
startGrails
script to use a different port number, connect using that one.startGrails
スクリプトを修正して別のポート番号を使うようにしていた場合、その番号を使ってください。In previous versions of Grails there was a以前のバージョンのGrailsにはgrails-debug
command. The command is still included in the distribution and is deprecated in favor of the-debug
switch to the standardgrails
command.grails-debug
コマンドがありました。 このコマンドはまだディストリビューションに含まれていますが、将来は廃止予定です。 標準のgrails
コマンドに対する-debug
スイッチが推奨されています。
grails-debug
スクリプトを修正し、suspend
オプションをn
からy
に変更します。
なお、JPDA(Java Platform Debugger Architecture)の接続設定については、http://java.sun.com/j2se/1.5.0/docs/guide/jpda/conninv.html#Invocationでより詳細を知ることができます。-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
の代わりに、-Xrunjdwp:transport=dt_socket,server=n,address=8000
が必要です。
(これはEclipseのリモートJavaアプリケーションに対するデフォルトポートを想定しています。)
Eclipseで新規に「Remote Java Application」を実行し、接続タイプを「Standard (Socket Listen)」として、「Debug」をクリックします。
これにより、Eclipseでデバッグセッションを起動したままにできるので、「Socket Attach」の再実行を忘れないように気を遣わずとも、自由にデバッグできます。
この場合、grails-debug
とgrails-debug-attach
という2つのスクリプトが便利に使えます。
20.3 Grailsコアにパッチを送る
フォークとプルリクエスト
変更用ローカルブランチを作成する
git checkout -b mine
master
ブランチからmine
という名前の新しいローカルブランチが作られます。
もちろん、ブランチの名前は好きなように付けてください。
mine
という名前を使う必要はありません。重要な変更についてはJIRAで課題を作成する
コミットログにJIRAの課題IDを含める
自分のフォークが最新であることを確認する
upstream
という名前でリモートに登録されたメインリポジトリがあり、そこに対してプルリクエストを送りたいとします。
また、すべての変更は現在、master
ブランチではなく、ローカルのmine
ブランチにあるとします。
まず最初に、前回フェッチしてマージした以降に追加されているすべての変更をメインリポジトリからプルする必要があります:git checkout master git pull upstream
master
に対して、ローカルブランチをリベースします:git checkout mine git rebase master
master
上の最新の変更の後に並んでいます。
いくつかのカードを、中に混ぜ込むのではなく、デッキの一番上に追加したイメージです。master
にきれいにマージすることができます:git checkout master git merge mine
git push
プルリクエストの理由を伝える
20.4 Grailsドキュメントにパッチを送る
ガイドをビルドする
./gradlew docs
GRADLE_OPTS
environment variable a value likeGRADLE_OPTS
環境変数を設定して、Gradleのメモリ使用量を増やした方が良いです。export GRADLE_OPTS="-Xmx512m -XX:MaxPermSize=384m"
./gradlew -Dgrails.home=/home/user/projects/grails-core docs
grails.home
property, then the build will fetch the Grails source - a download of 10s of megabytes. It must then compile the Grails source which can take a while too.grails.home
プロパティを指定しないと、ビルド時にGrailsのソースファイル(10数MBあります)をダウンロードします。
そしてそのGrailsソースコードをコンパイルするため、より時間がかかるのです。local.properties
ファイルを作成できます:grails.home=/home/user/projects/grails-core
grails.home=../grails-core
./gradlew -Ddisable.groovydocs=true docs
build/docs
directory, with the guide
sub-directory containing the user guide part and the ref
folder containing the reference material. To view the user guide, simply open build/docs/index.html
.build/docs
ディレクトリに作られます。
guide
サブディレクトリにはユーザーガイドが、ref
フォルダにはリファレンスが入ります。
ユーザーガイドを表示するためには、単にbuild/docs/index.html
を開きます。出力する
src/<lang>/guide
directory. Sections and sub-sections then go into directories with the same name as the chapter gdoc but without the suffix.src/<lang>/guide
ディレクトリ直下のgdocファイルです。
セクションやサブセクションは、各章のgdocファイル名からサフィックスを除いた名前のサブフォルダに格納します。src/<lang>/guide/toc.yml
file, which is a YAML file. This file also defines the (language-specific) section titles. If you add or remove a gdoc file, you must update the TOC as well!src/<lang>/guide/toc.yml
ファイルで定義されています。
このファイルは同時に各セクションの(各言語ごとの)タイトルも定義しています。
gdocファイルを追加・削除した場合、このTOCファイルも合わせて更新する必要があります!src/<lang>/ref
directory contains the source for the reference sidebar. Each directory is the name of a category, which also appears in the docs. Hence the directories need different names for the different languages. Inside the directories go the gdoc files, whose names match the names of the methods, commands, properties or whatever that the files describe.src/<lang>/ref
ディレクトリには「Quick Reference」というサイドバーのソースが格納されています。
各ディレクトリ名はカテゴリ名になっていて、カテゴリ名は本文にも現れます。
そのため、ディレクトリには言語ごとに違う名前が必要です。
そのディレクトリ内にgdocファイルが格納されます。gdocファイルの名前はメソッド名・コマンド名・プロパティ名やそのファイルが説明している何かに一致します。翻訳
src/en
being the main one. To add another one, simply create a new language directory under src
and copy into it all the files under src/en
. The build will take care of the rest.src/en
をオリジナルとして、さまざまな言語に翻訳されたユーザーガイドを提供しています。
新しい言語の翻訳を追加するには、単にsrc
ディレクトリに新しい言語のフォルダを作成し、src/en
にあるすべてのファイルをコピーします。
ビルドすることで必要な作業が行われます。{hidden}
macro to wrap the English text that you have replaced, rather than remove it. This makes it easier to compare changes to the English guide against your translation. For example:{hidden}
マクロで英語の原文を囲んでください。
これにより容易に英語の原文と今回の翻訳の比較ができます。たとえば:{hidden} When you create a Grails application with the [create-app|commandLine] command, Grails doesn't automatically create an Antbuild.xml
file but you can generate one with the [integrate-with|commandLine] command: {hidden}Quando crias uma aplicação Grails com o comando [create-app|commandLine], Grails não cria automaticamente um ficheiro de construção Ant
build.xml
mas podes gerar um com o comando [integrate-with|commandLine]:
diff
will show differences on the English lines. You can then use the output of diff
to see which bits of your translation need updating. On top of that, the {hidden}
macro ensures that the text inside it is not displayed in the browser, although you can display it by adding this URL as a bookmark: javascript:toggleHidden();
(requires you to build the user guide with Grails 2.0 M2 or later).diff
で英語の行についての変更を表示することができます。
つまり、翻訳のどこをアップデートすればいいかを知るためにdiff
の出力を使えるのです。
ブラウザで見るとき、{hidden}
に囲まれた部分は表示されません。
ただし、ブックマークとしてjavascript:toggleHidden();
を追加することで、{hidden}
に囲まれた部分を表示できるようになります。
(これにはGrails 2.0以降でユーザーガイドがビルドされている必要があります。)left_to_do.groovy
script in the root of the project to see what still needs translating. You run it like so:left_to_do.groovy
スクリプトをプロジェクトのルートで実行すれば、まだ翻訳が必要な箇所をしることができます。
このように実行します:./left_to_do.groovy es
{hidden}
blocks that hasn't changed since being translated will not appear in the diff output. In other words, all you will see is content that hasn't been translated yet and content that has changed since it was translated. Note that {code}
blocks are ignored, so you don't need to include them inside {hidden}
macros.{hidden}
ブロックに含まれていて、翻訳されたあと変更されていない部分は差分として出力されません。
言い換えれば、翻訳されたあと原文が修正されたのに、まだ再翻訳されていない部分が表示されます。
{code}
ブロックは無視されるため、{code}
ブロックを{hidden}
で囲む必要は ありません 。resources/doc.properties
ファイルに、次のように各言語に固有のエントリを追加します:es.title=El Grails Framework es.subtitle=...
<lang>
. will override the standard ones. In the above example, the user guide title will be El Grails Framework for the Spanish translation. Also, translators can be credited by adding a '<lang>.translators' property:<lang>.
で始まるプロパティは標準のプロパティを上書きします。
上記の例で言えば、スペイン語の翻訳ではユーザーガイドのタイトルが「El Grails Framework」となります。
同様に、翻訳者も<lang>.translators
プロパティを追加することでクレジットに名前を載せることができます:fr.translators=Stéphane Maldini
publishGuide_*
and publishPdf_*
tasks. For example, to build both the French HTML and PDF user guides, simply executepublishGuide_*
やpublishPdf_*
を使えば簡単にビルドできます。
たとえば、フランス語のHTMLとPDFのユーザーガイドをビルドするには、単純に以下を実行します:./gradlew publishPdf_fr
build/docs/fr
. You can then view the translated guide by opening build/docs/<lang>/index.html
.build/docs/fr
に作られます。
翻訳されたガイドは、build/docs/<lang>/index.html
を開けば見られます。21 翻訳レポート
Document Translation Report.
- File Count - 295
- Done - 281
- TODO - 12
- Not found or new - 2
Original document updated after translation.:
Not done.
- ../en/guide/commandLine/interactiveMode.gdoc
- ../en/guide/commandLine/wrapper.gdoc
- ../en/guide/links.yml
- ../en/guide/rewriteRules.txt
- ../en/guide/security/xssPrevention.gdoc
- ../en/guide/services/declarativeTransactions/transactionsRollbackAndTheSession.gdoc
- ../en/guide/theWebLayer/controllers/controllerExceptionHandling.gdoc
- ../en/guide/theWebLayer/urlmappings/namespacedControllers.gdoc
- ../en/guide/theWebLayer/urlmappings/redirectMappings.gdoc
- ../en/guide/theWebLayer/urlmappings/restfulMappings.gdoc
- (original file updated) ../en/guide/toc.yml
- ../en/guide/webServices/SOAP.gdoc
File not found (new file added) or empty file
- ../en/guide/gettingStarted.gdoc
- ../en/guide/theWebLayer.gdoc