When you save an entity with a key, it creates a new
entity in the data store with that key. As you found out
earlier, this creates a key conflict. If an entity with that key
already exists, it is out of luck and it gets chucked out.
It's overwritten in the data store. So if you want to update
an existing entity, first you need to get it out of the
data store, then you make your updates and then you save it
back into the data store again. So back here in the save profile
method of that conference API, whenever we've been saving our
profile the first thing we do is create a new
profile with the user ID. That means that actually every
time you update your profile, you're not really updating it,
you'll create a new profile entity which overrides the existing
profile entity. You can see how that plays out in
the API Explorer. Now that we've implemented get profile, we
can just call get profile to get the existing profile
for the current user. So lets do that. Okay. Lets see, so my display name
is "Chocolate Cake" and my t-shirt size is XL. Now, lets say I want to
change that, I want to change my t-shirt size, so I go to
saveProfile and the only thing I want to do is to change my
t-shirt size from XL to XS, extra small, this time.
Now we'll execute. And what would be really nice,
would be that the only thing that changes it
the t-shirt size. So let's see if it will
happen. But, no, that's not what happens. You see
how the display name gets set back to the
default, which is example and my t-shirt size did
change. What should really happen, the saveProfile method should
get the existing profile and only update the fields that
have changed. So that's going to be your next task.
Cuando guardan una entidad
con una clave,
aparece una nueva entidad
en el almacén con esa clave.
Como ya sabrán, esto da lugar
a un conflicto de claves.
Si ya existe una entidad
con esa misma clave, se descarta.
Se sobreescribe en el almacén de datos.
Para actualizar una entidad preexistente,
primero tómenla del almacén.
Luego actualícenla y después guárdenla
en el almacén.
Regresemos al método save profile
de la API conferencia.
Vayan donde esté guardado el perfil.
Primero se crea el nuevo perfil
con el ID de usuario.
Así, cuando se actualice el perfil,
en realidad no se actualiza,
sino que se crea una nueva entidad
de perfil que anula a la anterior.
Véanlo en API Explorer.
Ahora que hemos implementado getprofile
le indicamos
que tome el perfil preexistente
para el usuario actual.
Hagámoslo. Vale.
Mi nombre es "Chocolate Cake"
y mi talla de camiseta es la XL.
Ahora quiero cambiarlo.
Quiero cambiar mi talla de camiseta.
Voy a saveProfile
y lo único que quiero cambiar
es la talla de camiseta
de XL a XS, extra pequeña.
Ahora ejecutamos.
Estaría bien que lo único
que cambiase fuera la talla.
Veamos si sucede.
Pero no. Esto no ocurre.
Vean que vuelvo a tener
el nombre por defecto "example".
La talla de camiseta sí que cambia.
Lo que debería ocurrir es que
el método saveProfile
tomase el perfil preexistente
y solo actualizase los campos
que han cambiado.
Esa será su próxima tarea.
エンティティとキーを保存するとDatastore内で
そのキーを使って
新しいエンティティが作成されます
この時にキーの競合が発生するのでしたね
同じキーを持つエンティティが存在する場合には
新しいエンティティは拒否されます
エンティティはDatastore内で上書きされるため
エンティティを更新するためには
まずDatastoreから取り出して更新します
そしてDatastoreに戻して保存します
ConferenceApiの
saveProfileメソッドに戻りましょう
profileを保存する時には必ず最初に
ユーザIDを使って新しいprofileを作成します
つまりそのprofileを更新するのではなく
既存のProfileエンティティをオーバーライドする
新しいProfileエンティティを作成するのです
APIs Explorerで動作を確認できます
getProfileを実装したので
getProfileを呼び出せば
既存のprofileを取得できます
実行してみましょう
私のdisplayNameはChocolate Cakeで
teeShirtSizeはXLです
ではteeShirtSizeを変更するとします
まずはsaveProfileに移動します
やりたいことはteeShirtSizeの変更だけです
teeShirtSizeをXLからXSに変更します
実行します
teeShirtSizeだけが変更されるはずですね
結果を見てみましょう
期待した結果とは違います
displayNameがデフォルトのexampleに戻っています
teeShirtSizeは変更されています
本来saveProfileメソッドは
既存のprofileを取得して
変更があったフィールドだけを
更新しなければなりません
次の課題でやってみましょう
Se vocês salvam
uma entidade com uma chave,
ela cria uma nova entidade
no data store com esta chave.
Como descobrimos antes,
isso cria um conflito de chave.
Se uma entidade com essa chave já existe,
está sem sorte e vai para fora.
Será substituido no data store.
Se você deseja atualizar
uma entidade existente,
necessita tirar do data store,
em seguida, fazer suas atualizações e então salvá-lo
de volta para o data store.
Retorne aqui em salvar perfil
método desta conferência API,
sempre que estamos guardando
nosso perfil, a primeira coisa
a fazer é criar um novo
Perfil com a ID de usuário.
Isso significa que cada vez
que você atualizar seu perfil,
na verdade não está atualizando.
Você criara uma nova entidade de perfil,
que substitui a existente
entidade de perfil.
Você pode ver como isso se desenrola
no explorador de API.
Já implementamos como criar um profile,
podemos chamar para obter o perfil
para adquirir o perfil existente
para o usuário atual.
Vamos ver, meu nome exibido
é "Bolo de Chocolate" e o tamanho do meu t-shirt é XL.
Diremos que quero mudar,
quero mudar meu tamanho t-shirt,
vou ao saveProfile e
quero mudar
o tamanho da t-shirt de XL a XS,
extra pequeno.
Agora iremos executar.
E o que seria bom,
seria a única coisa que mudaria
o tamanho de camiseta.
Vamos ver se acontece.
Não é o que acontece.
Você vê como o nome de exibição
retorna ao padrão,
o exemplo é o tamanho
da minha t-shirt que mudou.
O que deveria acontecer,
o método de saveProfile deveria
obter o perfil existente e
atualizar só os campos que mudaram.
Então isso vai ser a sua próxima tarefa.