英文:
Best practice to add the ID to a datastore entity?
问题
使用 IncompleteKey 创建实体时,以确保每个记录在本质上是唯一的,最好的方法是将键添加回记录中,以便在创建时可以在结构中传递。
例如,像这样的代码(未经测试)是否是一个好主意,使用事务?
err = datastore.RunInTransaction(c, func(c appengine.Context) error {
incompleteKey := datastore.NewIncompleteKey(c, ENTITY_TYPE, nil)
entityKey, err := datastore.Put(c, incompleteKey, &MyStruct)
if err != nil {
return err
}
MyStruct.SelfID = entityKey.IntID()
_, err = datastore.Put(c, entityKey, &MyStruct)
return err
}, nil)
作为后续问题,我猜这几乎不会失败,因为它几乎不会在相同的 incompleteKey 上操作。
英文:
When creating an entity using an IncompleteKey so that each record is inherently unique, what is the best way to add the key back into the record so it can be passed around in the structure- at the time of creation?
For example, is something like this (untested code) a good idea, using Transactions?
err = datastore.RunInTransaction(c, func(c appengine.Context) error {
incompleteKey := datastore.NewIncompleteKey(c, ENTITY_TYPE, nil)
entityKey, err := datastore.Put(c, incompleteKey, &MyStruct)
if(err != nil) {
return err
}
MyStruct.SelfID = entityKey.IntID()
_, err = datastore.Put(c, entityKey, &MyStruct)
return err
}, nil)
As a followup- I'm guessing this should almost never fail since it will almost never operate over the same incompleteKey?
答案1
得分: 1
你不需要将MyStruct两次放入数据库中,这是不必要的开销。键作为实体的一部分存储,并且在需要时可以检索到。
文档中有一个很好的示例,说明如何存储实体并将其ID用作引用:https://cloud.google.com/appengine/docs/go/datastore/entities#Go_Ancestor_paths
当你想要获取实体的键时,可以使用以下方法:https://cloud.google.com/appengine/docs/go/datastore/queries#Go_Retrieving_results - (已编辑)请注意示例中的键和结构体是在一次操作中填充的。
如果你通过键查询实体,你已经知道它的ID。
因此,没有必要将ID作为单独的属性。如果你想将其与实体一起传递给业务逻辑,你可以创建一个包装器 - 可以使用interface()泛化为实体结构体,或者为每个实体结构体创建一个强类型的包装器。
英文:
You don't need to put the MyStruct into DB twice - it's unnecessary overhead. The key stored as a part of the entity and can be retrieved when needed.
There is a good example in docs on how to store an entity and used it ID as a reference: https://cloud.google.com/appengine/docs/go/datastore/entities#Go_Ancestor_paths
When you want to get keys for entities you can do this using this approach:
https://cloud.google.com/appengine/docs/go/datastore/queries#Go_Retrieving_results - (edited) notice in the example that keys and structs are populated in 1 operation.
If you query the an entity by key you already know it ID.
So there is no need to have an ID as a separate property. If you want to pass it around with the entity for your business logic you can create a wrapper - either generalized using interface() for the entity struct or a strongly typed (1 per each entity struct).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论