An Introduction to Grails 3 and GORM – Grails 3和GORM简介

最后修改: 2015年 12月 13日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This is a quick intro to Grails 3 and GORM.

这是对Grails 3和GORM的一个快速介绍。

We’re going to of course use Groovy and – implicitly – the framework also makes use of Hibernate for ORM, the Spring Framework for Dependency Injection, SiteMash for layout and themes, etc.

我们当然要使用Groovy,而且–隐含地–该框架还利用了Hibernate作为ORM,Spring框架作为依赖注入,SiteMash作为布局和主题,等等。

2. DataSource Configuration

2.数据源配置

We can start without having to specify any explicit data source configuration – by default Grails uses the HSQLDB database for the development and testing environments.

我们可以不用指定任何明确的数据源配置就开始了–默认情况下,Grails在开发和测试环境中使用HSQLDB数据库。

But if you want to change these defaults, you can define your selected data-source in the application.yml:

但如果你想改变这些默认值,你可以在application.yml中定义你所选择的数据源。

environments:
    development:
        dataSource:
             driverClassName : "com.mysql.jdbc.Driver"           
             url : "jdbc:mysql://localhost:8080/test"
             dialect : org.hibernate.dialect.MySQL5InnoDBDialect

Similarly we can create multiple environments here, next to development if we need to.

同样,如果需要,我们可以在这里创建多个环境,在development旁边。

3. Domain

3.域名

Grails is capable of creating the database structure for our domain classes, based on the dbCreate property in the database configuration.

Grails能够根据数据库配置中的dbCreate属性,为我们的领域类创建数据库结构。

Let’s define one of these domain classes here:

让我们在这里定义一个这样的领域类。

Class User {
    String userName
    String password
    String email
    String age
    static constraints = {
        userName blank: false, unique: true
        password size: 5..10, blank: false
        email email: true, blank: true
    }
}

Note how we’re specifying our validation constraints right in the model, which keeps things nice and clean, and annotation-free.

请注意我们是如何在模型中指定我们的验证约束的,这使事情变得漂亮、干净,而且无需注释。

These constraints will be checked by Grails automatically when the entity is being persisted and the framework will throw appropriate validation exceptions if any of these constraints are broken.

当实体被持久化时,Grails会自动检查这些约束,如果这些约束被破坏,框架会抛出适当的验证异常。

We can also specify GORM mappings in mapping property of the model:

我们还可以在模型的mapping属性中指定GORM映射。

static mapping = { sort "userName" }

Now if we call User.list() – we’ll get back results sorted by username.

现在,如果我们调用User.list() – 我们将得到用户名排序的结果。

We could of course achieve the same result by passing in the sort to the list API:

当然,我们可以通过向列表API传递排序来实现同样的结果。

User.list(sort: "userName")

4. CRUD Operations

4.CRUD操作

When we look at API operations, scaffolding plays a very interesting role in the beginning; it lets you generate basic a CRUD API for a domain class, including:

当我们看API操作时,scaffolding在一开始就扮演了一个非常有趣的角色;它让你为一个领域类生成基本的CRUD API,包括。

  • The necessary views
  • Controller actions for the standard CRUD operations
  • Two types: Dynamic and Static

Here’s how that works with dynamic scaffolding:

下面是如何使用动态脚手架的。

class UserController {
    static scaffold = true
}

By just writing this single line, the framework will generate 7 methods at runtime: show, edit, delete, create, save and update. These will be published as the API for that particular domain entity.

只要写下这一行,框架就会在运行时生成7个方法:显示、编辑、删除、创建、保存和更新。这些将作为该特定领域实体的API发布。

Example of Static scaffolding:

静态脚手架的例子。

  • To create a view with scaffolding use: “grails generate-views User
  • To create the controller and view with scaffolding use: “grails generate-controller User
  • To create everything in single command, use: “grails generate-all User

These commands will auto-generate the necessary plumbing for that particular domain object.

这些命令将为该特定域对象自动生成必要的管道。

Let’s now have a very quick look at using these operations – for example, for our User domain object.

现在让我们非常快速地看看如何使用这些操作–例如,对于我们的User域对象。

To create new “user” record:

创建新的 “用户 “记录

def user = new User(username: "test", password: "test123", email: "a@a.com", age: 14)
user.save()

To fetch a single record:

为了获取一条记录

def user = User.get(1)

This get API will retrieve the domain object in an editable mode. For a read-only mode, we can use the read API:

这个get API将以可编辑模式检索域对象。对于只读模式,我们可以使用read API。

def user = User.read(1)

To update existing record:

更新现有记录

def user = User.get(1)
user.userName = "testUpdate"
user.age = 20
user.save()

And a simple delete operation for an existing record:

还有一个对现有记录的简单删除操作。

def user = User.get(1)
user.delete()

5. GORM Queries

5 GORM查询

5.1. find

5.1.找到

Let’s start with the find API:

让我们从findAPI开始。

def user = User.find("from User as u where u.username = 'test' ")

We can also use a different syntax to pass in the parameter:

我们也可以使用不同的语法来传入参数。

def user = User.find("from User as u where u.username?", ['test'])

We can also use a named parameter:

我们也可以使用一个命名参数。

def user = User.find("from User as u where u.username=?", [username: 'test'])

5.2. findBy

5.2.findBy

Grails provides a dynamic finder facility which uses domain properties to execute a query at runtime and return the first matching record:

Grails提供了一个动态查找工具,它使用域属性在运行时执行查询,并返回第一个匹配记录。

def user = User.findByUsername("test")
user = User.findByUsernameAndAge("test", 20)
user = User.findByUsernameLike("tes")
user = User.findByUsernameAndAgeNotEquals("test", "100")

You can find more expressions here.

你可以找到更多的表达方式这里

5.3. Criteria

5.3.标准

We can also retrieve data using some flexible criteria:

我们还可以使用一些灵活的标准来检索数据。

def user = User.find { username == "test"}
def user = User.createCriteria()
def results = user.list {
    like ("userName", "te%")
    and 
    {
        between("age", 10, 20)
    }
    order("userName", "desc")
}

A quick note here – when using a criteria query, use “{ }” instead of “( )”.

在此简单说明一下–当使用标准查询时,使用”{ }”而不是”( )”。

5.4. Execute Query/Update

5.4.执行查询/更新

GORM also support the HQL query syntax – for read operations:

GORM也支持HQL查询语法–用于读取操作。

def user = User.executeQuery(
  "select u.userName from User u where u.userName = ?", ['test'])

As well as write operations:

以及写操作。

def user = User.executeUpdate("delete User u where u.username =?", ['test'])

6. Conclusion

6.结论

This has been a very quick intro to Grails and GORM – to be used as a guide to getting started with the framework.

这是对Grails和GORM的一个非常快速的介绍–可作为开始使用框架的指南。