【发布时间】:2014-12-14 23:18:00
【问题描述】:
我有这样的实体:User->Blague->Score 一个用户有很多 blagues(childs) 并且一个 blague 有一个分数。
我正试图从一个 blague 那里得到分数,但是当我写这个时:
User userPoster = ofy().load().type(User.class).id(5066549580791808L).now();
Blague blague = ofy().load().type(Blague.class).parent(userPoster).id(4609152743636992L).now();
Score score = ofy().load().type(Score.class).parent(blague).id(5735052650479616L).now();
resp.getWriter().println(userPoster);
resp.getWriter().println(blague);
resp.getWriter().println(score);
(ID 是正确的)得分为空,与 blague 和 userPoster 不同。为什么它是空的?
实体是这样创建的:
@ApiMethod(
name = "addBlague",
path = "addBlague",
httpMethod = ApiMethod.HttpMethod.POST)
public void addBlague(
@Named("category") EnumCategory category,
@Named("type") EnumType type,
@Named("lenght") EnumLenght lenght,
@Named("keywords") List<String> keywords,
@Named("text") String text,
@Named("userId") Long userId){
Key<User> userKey = Key.create(User.class, userId);
Blague blague = new Blague(category, type, lenght, text, userKey);
ofy().save().entity(blague).now();
Key<Blague> blagueKey = Key.create(Blague.class, blague.getId());
Score score = new Score(0, 0, blagueKey);
ofy().save().entity(score).now();
for (String word : keywords) {
KeyWord keyword = new KeyWord(word, blagueKey);
ofy().save().entity(keyword);
}
}
当然,课程也已注册。
如何从 blague 获得分数?
谢谢
编辑: 苏克雷密码:
package blagueur;
import java.util.HashMap;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.annotation.Parent;
@Entity
@Index
@Cache
public class Score {
@Id
private Long id;
private int likes;
private int dislikes;
private HashMap<String, Boolean> voters;
@Parent
private Key<Blague> blagueKey;
private Score() {}
public Score(int likes, int dislikes, Key<Blague> blague) {
this.likes = likes;
this.dislikes = dislikes;
this.blagueKey = blague;
this.voters = new HashMap<String, Boolean>();
}
public Long getId() {
return id;
}
public int getLikes() {
return likes;
}
public int getDislikes() {
return dislikes;
}
public void addVote(Long userId, boolean like){
voters.put(String.valueOf(userId), like);
if (like){
likes++;
}
else{
dislikes++;
}
}
public void removeVote(Long userId){
String id = String.valueOf(userId);
boolean like = voters.get(String.valueOf(userId));
voters.remove(String.valueOf(userId));
if (like){
likes--;
}
else{
dislikes--;
}
}
public Key<Blague> getBlagueKey() {
return blagueKey;
}
}
【问题讨论】:
-
您在
Score类型定义中是否有@Parent?也许向我们展示Score代码。 -
是的,我有,我在答案中添加了一个编辑以显示 socre 的代码
标签: google-app-engine google-cloud-endpoints objectify endpoints