是否有经济高效的实体设计教程?
如果我制作一个小样本,并说我想存储用户和群组。这些群组有用户列表。如果任何用户想要加入该组,我必须检查该组是否存在且该用户不属于该组。
我的问题不是如何做到这一点。问题在于良好的实体设计或良好的客观化使用。
以下是一些缩短的示例代码,我将如何执行此操作:
User.java
@Entity
@Cache
@Embed
public class User {
@Id Long id;
@Index String name;
String passwordHash;
}
Group.java
@Entity
@Cache
public class Group {
@Id Long id;
@Index Long groupAdministratorUserId;
@Index String name;
List<User> users = new ArrayList<User>();
@Index Boolean isPublic;
}
使用
if (!app.authenticate(getRequest(), getResponse()))
{
// Not authenticated
setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
}
else
{
Group newGroup = ofy().load().type(Group.class).id(Long.parseLong(id)).now(); // is it correct that the embedded data is already loaded?
// following check and insert is only for illustration!
newGroup.getUsers().contains(connectedUser);
newGroup.getUsers().add(connectedUser);
ofy().save().entity(newGroup).now();
}
我的“开销”(身份验证)
public class MyVerifier extends LocalVerifier {
private User fetched;
public User getFetched() {
return fetched;
}
@Override
public char[] getLocalSecret(String identifier) {
// this is behind search... and another list()
// User fetched = ofy().load().type(User.class).filter("name", userName).first().now();
fetched = User.searchByExactName(identifier);
if (fetched != null)
{
return fetched.getPasswordHash().toCharArray();
}
return null;
}
}
P.S。我知道来自Google的页面:https://code.google.com/p/objectify-appengine/wiki/BestPractices
但这不是我正在寻找的东西
答案 0 :(得分:0)
我会将User
实体的组ID列表存储起来。无需使用@Embed
。最佳解决方案实际上取决于您的应用程序中最常见的操作。根据你的说法,我会推荐以下内容:
@Entity
@Cache
public class User {
@Id long id;
String name;
String passwordHash;
List<Long> groups;
// constructor left out for brevity.
}
@Entity
@Cache
public class Group {
@Id long id;
long adminId;
String name;
boolean isPublic;
// constructor left out for brevity.
}
User user1 = new User(userName1, passwordHash1);
User user2 = new User(userName2, passwordHash2);
Key<User> user1Key = ofy().save().entity(user1).now(); // Create two users.
Key<User> user2Key = ofy().save().entity(user2).now(); // The don't have any groups yet.
long adminId = user1Key.getId();
Group group = new Group(name, adminId, isPublic)
Key<Group> groupKey = ofy().save().entity(group).now(); // Create a group
user2.addToGroup(groupKey.getId()); // This adds the group ID to the User.groups list.
ofy().save().entity(user2).now(); // Add user2 to group.
为了节省成本(特别是在更新期间的小型数据存储区操作),请确保创建尽可能少的索引。从少量@Index
es开始,并根据需要添加它们。