Home >Database >Mysql Tutorial >How to generate date and time in Java and store it in Mysql database
1. Three necessary fields for the table: id, gmt_create, gmt_modified
2.gmt_create is the creation time, gmt_modified is the update time
3.However, the default settings of creation time and update time should not be set by the database, and should be managed uniformly by the Handler of Mybatis-plus.
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. Entity class
@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. Entity class operation database time tool class
/** * @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. Test
@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); }
Operation successful:
The above is the detailed content of How to generate date and time in Java and store it in Mysql database. For more information, please follow other related articles on the PHP Chinese website!