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資料庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!