第一段引用上面的摘要:
在使用 Google app Engine 的 Go 语言环境中,数据存储的ID自动生成并非像某些ORM框架那样自动填充实体对象的ID字段。开发者需要理解 datastore.Put 方法返回的 Key 对象包含了新生成的ID,并手动将其赋值给实体对象。本文将详细介绍如何正确使用 incomplete key 来实现 ID 自动生成,并将其应用到你的数据模型中。
理解 App Engine 数据存储的 ID 生成机制
在使用 Google App Engine 的数据存储服务时,经常会遇到需要自动生成唯一ID的场景。与一些 ORM 框架不同,App Engine 的数据存储不会自动填充你的实体对象的 ID 字段。你需要手动从 datastore.Put 方法返回的 Key 对象中提取生成的 ID,并将其赋值给你的实体对象。
使用 Incomplete Key 实现 ID 自动生成
datastore.NewIncompleteKey 函数用于创建一个 incomplete key,这意味着在调用 datastore.Put 方法时,数据存储会自动生成一个唯一的 ID。这个 ID 会包含在 datastore.Put 返回的 Key 对象中。
以下是一个示例:
package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "cloud.google.com/go/datastore" ) // Participant 实体对象 type Participant struct { ID int64 `datastore:"-" json:"ID"` // 忽略存储,用于JSON输出 LastName string `json:"LastName"` FirstName string `json:"FirstName"` Birthdate string `json:"Birthdate"` Email string `json:"Email"` Cell string `json:"Cell"` } func serveError(w http.ResponseWriter, err error) { log.Printf("Error: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) } func handleParticipant(client *datastore.Client, parentKey *datastore.Key) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() switch r.Method { case "POST": d, err := ioutil.ReadAll(r.Body) if err != nil { serveError(w, err) return } participant := new(Participant) err = json.Unmarshal(d, &participant) if err != nil { serveError(w, err) return } // 创建 incomplete key key := datastore.NewIncompleteKey(ctx, "participant", parentKey) // 持久化数据 putKey, err := client.Put(ctx, key, participant) if err != nil { serveError(w, err) return } // 获取新生成的 ID participant.ID = putKey.ID() // 从数据库中获取数据 (可选,验证数据) if err = client.Get(ctx, putKey, participant); err != nil { serveError(w, err) return } // 发送给消费者 jsonData, err := json.Marshal(participant) if err != nil { serveError(w, err) return } w.Header().Set("Content-Type", "application/json") w.Write(jsonData) default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } } func main() { ctx := context.Background() // 替换为你的项目 ID projectID := "your-project-id" client, err := datastore.NewClient(ctx, projectID) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer client.Close() // 可选的 parent key var parentKey *datastore.Key = nil http.HandleFunc("/participant", handleParticipant(client, parentKey)) port := "8080" log.Printf("Listening on port %s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } }
代码解释:
- Participant 结构体: ID 字段使用了 datastore:”-” tag,表明它不会被直接存储到数据存储中。json:”ID” tag则用于JSON序列化输出。
- datastore.NewIncompleteKey: 创建一个 incomplete key,指定了 kind 为 “participant” 和可选的 parent key。
- datastore.Put: 将实体对象存储到数据存储,并返回一个包含新生成 ID 的 Key 对象。
- putKey.ID(): 从返回的 Key 对象中提取新生成的 ID,并赋值给 participant.ID。
- JSON序列化: 将包含新 ID 的 participant 对象序列化为 JSON 响应。
注意事项
- ID 字段的类型: ID 字段应该使用 int64 类型。
- Parent Key: 如果你的数据模型需要使用 parent key,请确保正确设置。
- 数据一致性: 在生产环境中,建议在存储数据后,从数据库中重新获取数据,以确保数据的一致性。
总结
App Engine 的数据存储的 ID 自动生成机制需要手动从 Key 对象中提取 ID。通过使用 datastore.NewIncompleteKey 和 putKey.ID(),你可以轻松地实现 ID 自动生成,并将生成的 ID 赋值给你的实体对象。 这种方式赋予了开发者对ID生成的更多控制权,也更符合Go语言的设计哲学。
js json go go语言 app ai switch win google json 结构体 Go语言 对象 数据库 kind