springboot jpa 创建、更新时间戳
****************************
相关注解
@CreationTimestamp
@ValueGenerationType(
generatedBy = CreationTimestampGeneration.class
)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface CreationTimestamp {
}
@UpdateTimestamp
@ValueGenerationType(
generatedBy = UpdateTimestampGeneration.class
)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface UpdateTimestamp {
}
***************************
示例
****************
pojo 层
Person
@Entity
public class Person {
private Integer id;
private String name;
private Integer age;
private Timestamp createTime;
private Timestamp updateTime;
@Id
@Column(name = "id", nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "name", nullable = false, length = 12)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "age", nullable = false)
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Basic
@Column(name = "create_time", nullable = true)
@CreationTimestamp
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
@Basic
@Column(name = "update_time", nullable = true)
@UpdateTimestamp
public Timestamp getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
。。。。
}
****************
controller层
PersonController
@RestController
public class PersonController {
@Autowired
private PersonRepository personRepository;
@RequestMapping("/save")
public String save(){
for(int i=0;i<10;i++){
Person person=new Person();
person.setId(i+1);
person.setName("瓜田李下"+i);
person.setAge(i);
personRepository.save(person);
}
return "success";
}
@RequestMapping("/update")
public Person update(){
Person person=personRepository.getOne(1);
person.setName("海贼王");
personRepository.save(person);
return person;
}
}
****************************
执行/save,/update后,数据库显示