Auto generating keys
本章节描述了如何使用内置机制自动生成 Couchbase 文档键。支持两种类型的自动生成策略。
This chapter describes how couchbase document keys can be auto-generated using builtin mechanisms. There are two types of auto-generation strategies supported.
Couchbase 支持的最大键长度为 250 字节。 |
The maximum key length supported by couchbase is 250 bytes. |
Configuration
要自动生成的键应使用 @GeneratedValue
进行注释。默认策略为 USE_ATTRIBUTES
。可以作为实体本身的一部分提供键的前缀和后缀,这些值不会持久化,它们仅用于键生成。前缀和后缀使用 order
值进行排序。默认顺序为 0
,多个没有顺序的前缀将覆盖上一个。如果 id 的值已经可用,则将跳过自动生成。连接符可以使用 delimiter
提供,默认连接符为“.”。
Keys to be auto-generated should be annotated with @GeneratedValue
.
The default strategy is USE_ATTRIBUTES
.
Prefix and suffix for the key can be provided as part of the entity itself, these values are not persisted, they are only used for key generation.
The prefixes and suffixes are ordered using the order
value.
The default order is 0
, multiple prefixes without order will overwrite the previous.
If a value for id is already available, auto-generation will be skipped.
The delimiter for concatenation can be provided using delimiter
, the default delimiter is .
.
@Document
public class User {
@Id @GeneratedValue(strategy = USE_ATTRIBUTES, delimiter = ".")
private String id;
@IdPrefix(order=0)
private String userPrefix;
@IdSuffix(order=0)
private String userSuffix;
...
}
Key generation using attributes
使用文档属性的组合来生成密钥是一种常见的做法。使用属性生成密钥会基于提供的排序(类似于前缀和后缀)连接所有带 IdAttribute
注释的属性值。
It is a common practice to generate keys using a combination of the document attributes.
Key generation using attributes concatenates all the attribute values annotated with IdAttribute
, based on the ordering provided similar to prefixes and suffixes.
@Document
public class User {
@Id @GeneratedValue(strategy = USE_ATTRIBUTES)
private String id;
@IdAttribute
private String userid;
...
}
Key generation using uuid
这种自动生成使用 UUID 随机生成器生成消耗 16 个字节键空间的文档键。此机制仅适用于测试框架。
This auto-generation uses UUID random generator to generate document keys consuming 16 bytes of key space. This mechanism is only recommended for test scaffolding.
@Document
public class User {
@Id @GeneratedValue(strategy = UNIQUE)
private String id;
...
}