I am new to Spring boot. I am planning to use postgresql database. I am using spring data JPA
In this entity, I need to add these fields
@Entity
@Table(name="STUDENT")
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(name="STUDENT_NAME", length=50, nullable=false, unique=false)
private String name;
Here i want to add
createdby, modifiedby <--
createdat, modifiedat <-- (i want them to be timezone aware)
// other fields, getters and setters
}
How can i do this.
I am coming from django background there we just do there
class Student(models.Model):
... other fields
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
created_by = models.ForeignKey(User,related_name="%(app_label)s_%(class)s_created_by",on_delete=models.CASCADE)
You can use the @PrePersist
and @PreUpdate
methods. For example:
@Entity
public class SomeEntity {
//..other properties..//
private LocalDateTime createDate;
private LocalDateTime modifyDate;
private String createdBy;
private String modifiedBy;
@PrePersist
private void beforeSaving() {
createDate = LocalDateTime.now();
createdBy = Thread.currentThread().getName(); //todo: put your logic here
}
@PreUpdate
private void beforeUpdating() {
modifyDate = LocalDateTime.now();
modifiedBy = Thread.currentThread().getName(); //todo: put your logic here
}
}
Additionally, if you wanna use such methods in all of your entities you can create BaseEntity
and extend it in other classes, for example:
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private LocalDateTime createDate;
private LocalDateTime modifyDate;
private String createdBy;
private String modifiedBy;
@PrePersist
private void beforeSaving() {
createDate = LocalDateTime.now();
createdBy = Thread.currentThread().getName(); //todo: put your logic here
}
@PreUpdate
private void beforeUpdating() {
modifyDate = LocalDateTime.now();
modifiedBy = Thread.currentThread().getName(); //todo: put your logic here
}
//..getters/setters omitted..//
}
and
@Entity
public class SomeEntity extends BaseEntity{
//..other properties..//
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.