I have to auto generate timestamp when I am creating a new record and auto generate modified timestamp when I update a record.
can anybody tell me how do I implement this. I am using openJPA.
thanks in advance.
You can use the following code:
#Column
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#Column
#Temporal(TemporalType.TIMESTAMP)
private Date lastModificationDate;
// getters, setters
#PrePersist
void updateDates() {
if (creationDate == null) {
creationDate = new Date();
}
lastModificationDate = new Date();
}
The easiest is to use #Version annotation (documentation here)
Just add the following to your entities:
#Version
private java.sql.Timestamp myTimestamp;
/// normal getters & setters here
And it will do it automatically
Related
I have a entity like this
#Entity
#Table(name = "PAYMENT")
public class PaymentSummary {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "payment_id", nullable = false, unique = true)
private Long id;
#Column(name = "date_created", nullable = false)
private LocalDateTime createdDate;
#OneToOne
#JoinColumn(name = "webOrder_id")
private WebOrder webOrder;
#Enumerated(EnumType.STRING)
#Column(name = "payment_type")
private PaymentType paymentType;
#Column(name = "amount")
private Double amount;
#Column(name = "username")
private String username;
}
and i have repository for this entity
#Repository
public interface PaymentRepository extends JpaRepository<PaymentSummary, Long> {
List<PaymentSummary> findAllByCreatedDate(LocalDateTime localDate);
}
Later i want to retrieve every payment was created in today
List<PaymentSummary> payments = paymentRepository.findAllByCreatedDate(LocalDateTime.now());
And it return null, i know because i pass LocalDateTime.now(), so it will find exact by Date-minus-second . I want to list all today payment , and still want to keep LocalDateTime createdDate, how can i handle this situation , do i need to write native query , or JPA support this ?
Thank you.
If you only need to store the date of the payment (year, month, day in month), and don't need time information (hour, minutes,...), you need to change LocalDateTime for LocalDate on your entity.
This way, you would have:
List<PaymentSummary> findAllByCreatedDate(LocalDate localDate);
And, using:
List<PaymentSummary> payments = paymentRepository.findAllByCreatedDate(LocalDate.now());
Would work.
If you need to store the date, and also the time information, you would need to use something like this:
List<PaymentSummary> findAllByCreatedDateBetween(LocalDateTime startDateTime, LocalDateTime endDateTime);
And call it with something like:
// 2020-04-12T00:00.000
LocalDateTime startDateTime = LocalDateTime.of(LocalDate.now() , LocalTime.MIN);
// 2020-04-12T23:59.999
LocalDateTime endDateTime = LocalDateTime.of(LocalDate.now() , LocalTime.MAX);
List<PaymentSummary> payments = paymentRepository.findAllByCreatedDateBetween(startDateTime, endDateTime);
It will return null because LocalDateTime.now() will create the current date and time. In your case I think you need to return by date only
It`s possible to create one JsonSerialize and Deserialize with spring boot?
I put in my appliation.properties this line
spring.jackson.date-format=dd/MM/yyyy HH:mm:ss
but when I return one Date he allways returns a wrong value (yyyy-MM-dd) so I try to create one custom serialization following the http://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/htmlsingle/#boot-features-json-components
but don`t work.
this is my return:
#Entity
#Table(name = "view_atos_praticados", catalog="db_registro", schema="db_wsprefeituraatos")
public class ViewAtosPraticados {
#JsonIgnore
#Id
#Column(name="id")
private Integer id;
#Column(name="descricao_ato")
private String ato;
#JsonIgnore
#Column(name="livro")
private String livro;
#JsonIgnore
#Column(name="numero_ato")
private Integer nrAto;
#JsonIgnore
#Column(name="numero_registro")
private String nrRegistro;
#Column(name="dat_registro")
private Date registro;
#Column(name="ic_transmissao")
private String transmite;
Try #JsonFormat annotation:
#JsonFormat(pattern="dd/MM/yyyy HH:mm:ss")
#Column(name="dat_registro")
private Date registro;
I want to exclude certain fields from a POST to my repositories.
For example I want to set the version myself so users cannot set this field themselves.
For example in the class below.
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#CreatedDate
private LocalDateTime created;
#LastModifiedDate
private LocalDateTime lastModified;
private String name;
}
I have tried to use the #ReadOnlyProperty annotation and not having a setter for the version field. But nothing worked, users can still set the version fields themselves. I have also tried to implement a global initializer like below, but without success. The binder gets picked up though.
#ControllerAdvice
public class GlobalInitializer {
#InitBinder
public void globalBinder(WebDataBinder webDataBinder) {
webDataBinder.setDisallowedFields("name");
}
}
You should place #JsonIgnore on field and on setter, and place #JsonProperty("propertyName") on getter.
Just tested - works for me:
#JsonIgnore
#LastModifiedDate
private LocalDate lastUpdated;
#JsonProperty("lastUpdated")
public LocalDate getLastUpdated() {
return lastUpdated;
}
#JsonIgnore
public void setLastUpdated(LocalDate lastUpdated) {
this.lastUpdated = lastUpdated;
}
I use #Audited annotation in Spring to have auditing about my update, create etc. on my db.
But I obtain on my database, a date-time with 2 hour less than real time, for example, I created a object and the I saved it, I have as create date-time: 2014-08-04 12:0 but I created it at 14:00.
This is my Auditor class, that every class audited extend:
#SuppressWarnings("serial")
#MappedSuperclass
public abstract class AbstractAudit implements Auditable<String, Long>, Serializable {
#Version
private int version;
#JsonIgnore
#Column(updatable=false)
private String createdBy;
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
#DateTimeFormat(iso=ISO.DATE_TIME)
#JsonIgnore
#Column(updatable=false)
private DateTime createdDate;
#JsonIgnore
private String lastModifiedBy;
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
#DateTimeFormat(iso=ISO.DATE_TIME)
#JsonIgnore
private DateTime lastModifiedDate;
//getter and setter method
}
How can I fix it??
Have I add some configuration on my project or on my server (Tomcat 7) ?
Thanks
Try to set this property in your jpa provider settings:
<prop key="jadira.usertype.databaseZone">jvm</prop>
Hope this helps.
Regards
thanks to you guys my knowlegde on hibernate has been improve dratiscally.
now i hit a block here about current_timestamp.
here is my codes
#Column(name="DATE_CREATED", insertable=false, updatable=false, columnDefinition="timestamp default current_timestamp")
#org.hibernate.annotations.Generated(value=GenerationTime.INSERT)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date dateCreated;
#Column(name="LAST_MODIFIED", insertable=false, updatable=false, columnDefinition="datetime")
#org.hibernate.annotations.Generated(value=GenerationTime.ALWAYS)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date lastModified;
i want date_created to get the current_timestamp and i want the lastmodified to insert the time for each updates.apparently i can't have 2 current_timestamp fields on the same table.Is there other ways to achieve that? thanks for reading
This is not related to Hibernate per se. Your annotations as specified above tell Hibernate that the values are going to be generated by the database and thus need to be reloaded after entity is inserted / updated.
If that's the way you want to go with, you need to configure your database (by creating a trigger, for example) to populate date_created / last_modified columns as needed.
Another approach is to not mark those fields as generated and instead update them in your java code. If you're using JPA (via Hibernate EntityManager), it's rather trivial to do this via #PrePersist / #PreUpdate callback method:
#PreUpdate
#PrePersist
public void updateTimeStamps() {
lastModified = new Date();
if (dateCreated==null) {
dateCreated = new Date();
}
}
You could achieve the same thing with hibernates #CreationTimestampand #UpdateTimestamp annotations e.g.
#Column(name = "CREATED")
#CreationTimestamp
private LocalDateTime created;
#Column(name = "LAST_UPDATED")
#UpdateTimestamp
private LocalDateTime lastUpdated;