Can you use the same String as the Key id for multiple models?
If I have three model classes - Taxpayer
, Criminal
and Patient
- can I use socialSecurityNumber
as the Key ID for all three or do I nee开发者_如何学Cd to make it unique even across model classes.
In other words, should it be like this:
String socialSecurityNumber = "123-45-6789";
Long now = new Long(System.currentTimeMillis()); // use time to create uniqueness
String name = now.toString() + "-" + socialSecurityNumber;
Key key = KeyFactory.createKey(getClass().getSimpleName(), name);
or this:
String socialSecurityNumber = "123-45-6789";
Key key = KeyFactory.createKey(getClass().getSimpleName(), socialSecurityNumber);
Yes. The key name forms only part of the key, along with the app ID, entity kind, and any ancestor keys, so it's fine to use the same key name in different models.
Be aware, however, that a social security number makes a poor primary key for several reasons:
- You probably shouldn't be collecting it from your users in the first place, and they may have the right to refuse to give it to you.
- Not everyone has an SSN - in particular, people who aren't US citizens, and even some US citizens too.
- They're not unique: old SSN numbers get recycled. In the early days of the SSN system, some duplicates were issued, too.
If it are separate tables and you are sure it are really primary keys (criminals have been known to use aliases) I see no real problems.
Mind you, I would still use a surrogate key as Id, but that is because I have become dogmatic in this area since I have seen to much "meaningful primary keys" suddenly change or the situations change so the primary keys are no longer primary keys.
In those cases having the key in a normal field (with a unique index constraint for example) there are more options to deal with whatever has happened.
精彩评论