我正在使用Grails 2.4并正在提供REST API。我正在寻找有关域/实体创建的建议。
我有4个简单的表格:
1) projects:
projectId (auto-increment, PK)
name
description
(some other fields but not important for my question I guess)
2) users:
userId (auto-increment, PK)
roleId (FK->roles/roleId)
username
(some other fields but not important for my question I guess)
3) project_users (join table for projects & users):
projectId FK->projects/projectId)
userId (FK->users/userId)
4) roles:
roleId (auto-increment, PK)
name
角色可以是用户,经理或管理员。一个项目可以有许多用户(角色“user”的多个用户和角色“manager”的1个用户)。
REST API(JSON)的使用者是项目列表(GET),其中包含每个项目的所有用户名(用户名不是userId)(所有用户。如果用户不是管理员,则无所谓)。他们还希望能够向项目添加新用户(PUT)。同时创建新项目(POST)。对于所有请求,JSON请求/响应都应包含用户名)我确实在寻找有关如何进行操作的建议。
为了熟悉Grails / REST,我已经定义了3个域(项目,用户和角色),并且对这些域的GET&POST JSON都可以正常工作(未完成域关系)。
然后要玩域关系,我尝试了“db-reverse-engineer”插件,它为以下具有关系的域提供了支持。
class Projects {
String name
String description
static hasMany = [userses: Users]
static mapping = {
id column: "project_id"
version false
}
static constraints = {
name unique: true
description nullable: true
}
}
class Users {
String username
Roles roles
static hasMany = [projectses: Projects]
static belongsTo = [Roles]
static mapping = {
id column: "user_id"
version false
}
static constraints = {
username maxSize: 32, unique: true
}
}
class Roles {
String name
static hasMany = [userses: Users]
static mapping = {
id column: "role_id", generator: "assigned"
version false
}
static constraints = {
name maxSize: 16, unique: true
}
}
现在,我不确定如何继续进行。我是否需要创建数据库 View (db不允许查看更新)和相应的 Controller ,并保存写入自定义代码。我只是几天才开始玩Grails&REST,所以请耐心等待我的基本问题。
最佳答案
Grails开发的一般策略是一个简单的MVC模式,您可以在其中使用 Controller 来构建模型并将其传递给 View 。对于REST API,除非您需要更改域对象的默认显示方式,否则您实际上不需要 View 。您将需要为您的请求配置一些映射,这些映射将在here中讨论。除此之外,如果您需要除基本操作之外的任何业务逻辑,您还需要 Controller 和服务。对于您的域层,有一些建议:
1)通常将具有重要意义的域类和数据库表设为单数,这样就可以避免使用诸如useres之类的名称。因此,我将使您的表成为用户,角色和项目。
2)您与用户和项目之间存在多对多关系,因此需要指定该关系。您可以在映射中使用joinTable进行此操作,但是如果您经常查询该关系,则可能希望为ProjectUser创建一个单独的域类,因为如果不小心,则会遇到休眠n + 1问题。
希望能有所帮助,
关于grails - Grails 2.4-领域建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24333046/