Java怎么生成日期时间存入Mysql数据库

一、创建数据库标准

1.表的必备三个字段:id、gmt_create、gmt_modified

2.gmt_create是创建时间,gmt_modified是更新时间

3.然而创建时间和更新时间的默认设置不要让数据库来设置、统一用Mybatis-plus的Handler管理

二、数据库表结构

CREATE TABLE `ums_member` (
  `id` bigint(20) NOT NULL,
  `username` varchar(64) DEFAULT NULL,
  `password` varchar(64) DEFAULT NULL,
  `icon` varchar(500) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `nick_name` varchar(200) DEFAULT NULL,
  `note` varchar(500) DEFAULT NULL,
  `gmt_create` datetime DEFAULT NULL,
  `gmt_modified` datetime DEFAULT NULL,
  `login_time` datetime DEFAULT NULL,
  `status` int(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

三、使用步骤

1.实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "ums_member")
public class UmsMember implements Serializable {
    @TableId(value = "id", type = IdType.NONE)
    private Long id;

    @TableField(value = "username")
    private String username;

    @TableField(value = "password")
    private String password;

    @TableField(value = "icon")
    private String icon;

    @TableField(value = "email")
    private String email;

    @TableField(value = "nick_name")
    private String nickName;

    @TableField(value = "note")
    private String note;

    @TableField(value = "gmt_create",fill = FieldFill.INSERT)
    private Date gmt_create;

    @TableField(value = "gmt_modified",fill = FieldFill.INSERT_UPDATE)
    private Date gmt_modified;

    @TableField(value = "login_time")
    private Date loginTime;

    @TableField(value = "status")
    private Integer status;

    private static final long serialVersionUID = 1L;
}

2.实体类操作数据库时间工具类

/**
 * @author :Mr.ZJW
 * @date :Created 2022/3/2 10:08
 * @description:数据库自动插入时间工具类
 */
@Component
public class MyHandler implements MetaObjectHandler {

    public void insertFill(MetaObject metaObject) {
        System.out.println("添加插入时间");
        this.setFieldValByName("gmt_create",new Date(),metaObject);
        this.setFieldValByName("gmt_modified",new Date(),metaObject);
    }

    public void updateFill(MetaObject metaObject) {
        System.out.println("更新插入时间");
        this.setFieldValByName("gmt_modified",new Date(),metaObject);
    }
}

3.测试

@SpringBootTest
@RunWith(SpringRunner.class)
public class UmsMeberTest {

    @Autowired
    private UmsMemberMapper umsMemberMapper;

    @Test
    public void test01(){
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername("jowell");
        umsMember.setStatus(0);
        umsMember.setPassword("jowell");
        umsMember.setNote("not");
        umsMember.setNickName("cike");
        umsMember.setEmail("2280252534@qq.com");
        umsMemberMapper.insert(umsMember);
    }

操作成功:

以上就是Java怎么生成日期时间存入Mysql数据库的详细内容,更多请关注其它相关文章!