Domanda

Assume a model named User:

@Entity
public class User extends Model {
    @Id
    @Constraints.Min(10)
    public Long id;

    @Constraints.Required
    public String username;

    @Constraints.Required
    public String password;

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

When I attempt to update an instance of User in my controller:

    User user = User.find.where().eq("username", username).findUnique();

    if(user != null) {
        user.username = "some_new_username";
        user.save();
    }

no changes seem to be committed. I read somewhere that when you alter a model instance by its property, it does not get dirty and therefore no changes take place. Hence you should use a setter instead. In the documentation of Play Framework it is said that those setters (and getters) are generated automatically, but using user.setUsername(username) gives me a compilation error:

cannot find symbol [symbol: method setUsername(java.lang.String)] [location: class models.User]

Am I missing something?

È stato utile?

Soluzione

Have you tried adding custom setters?

@Entity
public class User extends Model {
    @Id
    @Constraints.Min(10)
    public Long id;

    @Constraints.Required
    public String username;

    public void setUsername(String _username) {
        username = _username;
    }

    @Constraints.Required
    public String password;

    public void setPassword(String _password) {
        password = _password;
    }

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

Altri suggerimenti

As far as I can tell, automatic getter/setter translation is broken in Play2. Your assignment:

user.username = "some_new_username";

should have triggered the function call:

user.setUsername("some_new_username");

This translation seems to be broken in Play 2. Here's my own question on the subject.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top