duanfu1873 2015-09-24 14:44
浏览 1
已采纳

将ID添加到数据存储实体的最佳实践?

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条回答 默认 最新

  • dsaf32131 2015-09-25 09:20
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私