mysql自动控制插入和更新时间
表设计
create table `product_category` (
`category_id` int not null auto_increment,
`category_name` varchar(64) not null comment '类目名字',
`category_type` int not null comment '类目编号',
`create_time` timestamp not null default current_timestamp comment '创建时间',
`update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间',
primary key (`category_id`)
);
create_time、update_time使用mysql自己记录时间的功能
java实体类设计
package com.imooc.dataobject;
import lombok.Data;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
@DynamicUpdate
@Data
public class ProductCategory {
/** 类目id. */
@Id
@GeneratedValue
private Integer categoryId;
/** 类目名字. */
private String categoryName;
/** 类目编号. */
private Integer categoryType;
public ProductCategory() {
}
public ProductCategory(String categoryName, Integer categoryType) {
this.categoryName = categoryName;
this.categoryType = categoryType;
}
}
无需增加createTime updateTime字段
@DynamicUpdate 注解可以让updateTime自动更新
本文介绍如何利用MySQL的特性实现表中记录的创建时间和更新时间自动维护。通过具体表设计示例,展示了如何设置create_time和update_time字段以默认当前时间,并在更新时自动更新时间戳。同时介绍了对应的Java实体类设计,利用@DynamicUpdate注解实现无需手动维护时间字段。
1282

被折叠的 条评论
为什么被折叠?



