跳到主要内容

唯一键

简介

校验请求参数映射的一列或一组列中的值是唯一的。

示例

假设有人力资源系统部门表,表结构如下

CREATE TABLE `departments` (
`dept_no` char(4) NOT NULL,
`dept_name` varchar(40) NOT NULL,
PRIMARY KEY (`dept_no`),
UNIQUE KEY `dept_name` (`dept_name`)
)

检查规则约束

  • 部门编号作为主键字段,具备唯一性,主键更多详见主键
  • 部门名称dept_name作为唯一键,具有唯一性

示例1:成功请求

新增一条部门名称在数据表中不存在的记录

POST http://127.0.0.1:21000
Content-Type: application/json;charset=utf-8
{
"jsonrpc": "2.0",
"method": "hrm.departments.add",
"params": {
"deptNo": "d234",
"deptName": "Human Resources"
},
"id": "client-unique-request-id"
}

响应

以上请求响应结果,插入成功返回对象包含主键名和值

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"jsonrpc": "2.0",
"result": {
"deptNo": "d234"
},
"id": "client-unique-request-id"
}

示例2:失败请求--部门名称已经存在

现在我们尝试新增一条同名的部门记录

POST http://127.0.0.1:21000
Content-Type: application/json;charset=utf-8
{
"jsonrpc": "2.0",
"method": "hrm.departments.add",
"params": {
"deptNo": "d235",
"deptName": "Human Resources"
},
"id": "client-unique-request-id"
}

响应结果

HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{
"jsonrpc": "2.0",
"error": {
"code": -32600,
"message": "checking for unique key conflicts: duplicate unique key in hrm.departments map[deptName:Human Resources]",
"data": {
"errorCode": "EU.Constraint.UK.Duplicated",
"errorDetails": [
{
"constraint": "UniqueKeyDuplicated",
"field": "deptName",
"fieldValue": "Human Resources",
"location": "hrm.departments",
"message": "duplicate unique key in hrm.departments.dept_name Human Resources"
}
],
"errorMessage": "duplicate unique key in hrm.departments map[deptName:Human Resources]"
}
},
"id": "client-unique-request-id"
}

可见dept_name存在重复了,唯一键约束校验失败,该请求被拦截,Luwak拒绝写入。

以上示例 Tested on Luwak 1.12.9