我有一个用户登录的Web应用程序。我希望用户能够添加朋友(以社交网络风格)。但是,我不确定如何使用游戏来解决这个问题。当我转到视图时,抛出空指针异常。
这是我尝试过的事情
@Entity
public class User extends Model {
@Id
public String username;
public String password;
public List<User> friends = new ArrayList<User>();
public static Finder<String, User> find = new Finder<String, User>(String.class, User.class);
public User(String username, String password){
this.username = username;
this.password = password;
}
public void addFriend(User friend){
friends.add(friend);
}
public static void befriend(String user1, String user2){
User.find.ref(user1).addFriend(User.find.ref(user2));
User.find.ref(user2).addFriend(User.find.ref(user1));
User.find.ref(user1).save();
User.find.ref(user2).save();
}
}
以下是观点:
@(friends: List[User])
<div id="current_friends">
@for(friend <- friends) { <!--This is the line the error is thrown at-->
@friend.username
}
</div>
要尝试对此进行测试,当应用程序启动时,我会创建两个用户并与他们成为朋友。
public class Global extends GlobalSettings {
@Override
public void onStart(Application app){
// Check if the database is empty
if(User.find.findRowCount()==0){
User conor = new User("Conor", "secret");
User jerry = new User("Jerry", "secret");
User.befriend("Conor", "Jerry");
conor.save();
jerry.save();
}
}
}
以下是控制器调用视图的方式:
return ok(index.render(User.find.byId(request().username()).friends));
所以我的问题是,为什么我的ArrayList在声明它时被初始化时总是为空?
答案 0 :(得分:1)
您正在尝试将数据库存储在数据库中,而Play不支持该数据库。 看看:@ElementCollection not supported
当你想使用&#34; plain&#34; JPA而不是来自Play的ebean
@ElementCollection
List<String> stuff;
但是无法存储复杂的对象,例如你的朋友&#34;对象作为数据库中的朋友列表。 这是您需要关联的地方 在这种情况下,很可能ManyToMany将是正确的搜索关键字。 Play Example @ManyToMany