anima icon indicating copy to clipboard operation
anima copied to clipboard

对模型执行update操作后id属性被置为NULL

Open Littlefisher619 opened this issue 4 years ago • 2 comments

表结构

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `activated` tinyint(1) NULL DEFAULT 0,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

User模型

@Table(name = "t_user")
public class User extends Model {

    private Integer id;
    private String username;
    private String password;
    private String email;
    private boolean activated;

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }



    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    public boolean getActivated() { return activated; }

    public void setActivated(boolean activated) { this.activated = activated; }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", activated=" + activated +
                '}';
    }
}

例如执行: user.setActivated(true); user.update(); 在执行完update之后,user模型的Id属性被置为NULL

Littlefisher619 avatar Jun 02 '19 12:06 Littlefisher619

+1,这个问题各个model基本都会碰到,XXX().update(); 之后id就null了

shuangbofu avatar Dec 29 '19 09:12 shuangbofu

自己包一层可以解决save/update的id null的情况,然后继承自己的Model

@Accessors(chain = true)
public class Model extends io.github.biezhi.anima.Model {

    @Getter
    @Setter
    private Long id;
    private long _id;

    @Override
    public ResultKey save() {
        ResultKey key = super.save();
        setId(key.asBigInteger().longValue());
        return key;
    }

    @Override
    public int update() {
        _id = getId();
        int update = super.update();
        setId(_id);
        return update;
    }
}

shuangbofu avatar Dec 29 '19 10:12 shuangbofu