javamodelplayframeworkupdatemodel

Models not being saved in Play Framework


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?


Solution

  • 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
        );
    }