简单grails增删改查
时间: 2023-09-20 13:09:32 浏览: 78
Grails 是一个基于 Groovy 语言的 Web 应用框架,它采用了 Convention over Configuration 的思想,可以快速开发出高质量的 Web 应用。下面是 Grails 中的增删改查操作的示例代码:
创建一个 domain 类
```groovy
class Book {
String title
String author
Integer pages
static constraints = {
title(blank: false)
author(blank: false)
pages(nullable: true)
}
}
```
创建一个控制器类
```groovy
class BookController {
// 列出所有的书籍
def index() {
def books = Book.list()
[books: books]
}
// 显示单个书籍
def show() {
def book = Book.get(params.id)
[book: book]
}
// 创建新的书籍
def create() {
def book = new Book(params)
if (book.save()) {
redirect(action: "show", id: book.id)
} else {
render(view: "index")
}
}
// 更新一本书籍
def update() {
def book = Book.get(params.id)
book.properties = params
if (book.save()) {
redirect(action: "show", id: book.id)
} else {
render(view: "edit", model: [book: book])
}
}
// 删除一本书籍
def delete() {
def book = Book.get(params.id)
book.delete()
redirect(action: "index")
}
}
```
创建一个视图文件
```html
<!-- 列出所有的书籍 -->
<g:each in="${books}" var="book">
<p>${book.title} by ${book.author}</p>
</g:each>
<!-- 显示单个书籍 -->
<h1>${book.title}</h1>
<p>Author: ${book.author}</p>
<p>Pages: ${book.pages}</p>
<!-- 创建新的书籍 -->
<g:form controller="book" action="create">
<label>Title: <g:textField name="title" /></label>
<label>Author: <g:textField name="author" /></label>
<label>Pages: <g:textField name="pages" /></label>
<g:submitButton name="save" value="Save" />
</g:form>
<!-- 更新一本书籍 -->
<g:form controller="book" action="update" id="${book.id}">
<label>Title: <g:textField name="title" value="${book.title}" /></label>
<label>Author: <g:textField name="author" value="${book.author}" /></label>
<label>Pages: <g:textField name="pages" value="${book.pages}" /></label>
<g:submitButton name="save" value="Save" />
</g:form>
<!-- 删除一本书籍 -->
<g:form controller="book" action="delete" id="${book.id}">
<g:submitButton name="delete" value="Delete" />
</g:form>
```
以上代码演示了 Grails 中的基本的增删改查操作。在实际开发中,需要根据业务需求进行修改和扩展。
阅读全文