1

这似乎是一个非常基本的问题,但我有一个模型(用户),我想存储一个字符串数组列表(它们是其他用户的 id)。我这样声明列表:

 public List<String> friends = new ArrayList<String>();

在向数组添加条目后,我保存了用户。但是当我尝试使用它时,朋友总是为空。是否有特定的方法来保存 ArrayList?任何帮助,将不胜感激。

我的模型:

@Entity
public class User extends Model {

@Id
public String username;
public String password;

public List<String> friends = new ArrayList<String>();

public static Finder<String, User> find = new Finder<String, User>(String.class, User.class);

// Constructor
public User(String username, String password){
    this.username = username;
    this.password = password;
}

// Methods
public void addFriend(String friend){
    friends.add(friend);
}

// Static Methods
public static User authenticate(String username, String password){
    return find.where().eq("username", username).eq("password", password).findUnique();
}

public static void befriend(String user1, String user2){
    User.find.ref(user1).addFriend(user2));
    User.find.ref(user2).addFriend(user1);

    User.find.ref(user1).save();
    User.find.ref(user2).save();
}

}

控制器方法:

return ok(index.render(
        User.find.byId(request().username()).friends,
));

还有一个非常简单的观点:

@(friends: List[User])

<div id="current_friends">
    @for(friend <- friends) {
        @friend.username
    }
</div>
4

3 回答 3

1

您需要使用 '手动' 保存关系saveManyToManyAssociations(String fieldname),例如:

public static void befriend(String userName1, String userName2){

    User user1 = User.find.byId(userName1);
    User user2 = User.find.byId(userName2);

    user1.friends.add(user2);
    user2.friends.add(user1);

    user1.save();
    user2.save();

    // here...
    user1.saveManyToManyAssociations("friends");
    user2.saveManyToManyAssociations("friends");

}

(注意:从我的顶部写的,所以请自己调试)

于 2013-05-26T12:29:25.290 回答
0

我遇到了完全相同的问题,这就是我解决它的方法(附带一些解释)。

实际上,您尝试将 ArrayList(因此大小未定义)保存在数据库中。显然(而且非常合乎逻辑),Play Framework 并不喜欢它;您必须使用注释或瞬态类。我决定用class的方式(也是因为我不知道怎么用注解做分表,所以没有冒险,但也不是最好的做法。其实是一个可怕的做法。但是,它仍然是)。

在您的情况下,您可以这样做:

@Entity
public class Friends extends Model {
    @Id
    public Long id;
    @Required
    public String user1;
    @Required
    public String user2;

    public static Finder<Long, Friends> find = new Finder<Long, Friends>(Long.class, Friends.class);

    //Here put your functions, I myself only added an insert method for the moment :

    public static void add(String user1, String user2){
        Friends f = new Friends();
        f.user1 = user1;
        f.user2 = user2;
        bu.save();
    }
}

在您的用户模型中,只需通过此功能更改将两个用户保存到彼此列表中的部分。

希望这会有所帮助。

注意:id在这里是因为我喜欢数字id,请随意更改。

注 2:当然,使用 @ManyToOne 和 @OneToMany 注释会好得多,但正如我之前写的,我不知道它是如何工作的。

于 2014-04-25T15:50:13.370 回答
0

此问题的一个潜在原因可能是您的观点:

你的观点的第一行是

@(friends: List[User])

用户没有包名,可能会导致空指针异常。在我的例子中,我的用户 bean 在模型包下,所以我有以下行:

@(friends: List[models.User])
于 2013-05-26T06:27:05.283 回答