spring data jpa selecting values considering the date and time - java

I have an entity which is
#AllArgsConstructor
#NoArgsConstructor
#Data
#Entity
#Table(name = "REFRESH_TOKENS")
public class JwtRefreshToken {
#Id
#Column(name = "TOKEN")
private String token;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", nullable = false)
private Tbluser user;
#Column(name = "EXPIRATIONDATETIME")
private LocalDateTime expirationDateTime;
public JwtRefreshToken(String token) {
this.token = token;
}
}
and the the corresponding repository is
JwtRefreshToken findByTokenAndAndExpirationDateTimeBefore( String token, #Param("expirationDateTime") LocalDateTime localDateTime);
The interesting thing here is the query always returns value even though the time has exceeded.
for example the value stored in database is 2019-04-21 22:33:08
and my current date time is 2019-04-21T23:02:43.971
but yet the above findByTokenAndAndExpirationDateTimeBefore returns value.
i want to compare the time as well.

You can enable debug output to see parameterized query and its parameters, add to your application properties
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Probably, you will get some clues if query does not use #Param("expirationDateTime") LocalDateTime localDateTime at all or there is timezone issue or everything is fine and you just misinterpret results ;)

Related

Is there any alternative for #CreationTimeStamp and #UpdateTimeStamp in hibernate 4.x.x? [duplicate]

For a certain Hibernate entity we have a requirement to store its creation time and the last time it was updated. How would you design this?
What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)? Will the data types be timezone-aware?
What data types would you use in Java (Date, Calendar, long, ...)?
Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?
What annotations would you use for the mapping (e.g. #Temporal)?
I'm not only looking for a working solution, but for a safe and well-designed solution.
If you are using the JPA annotations, you can use #PrePersist and #PreUpdate event hooks do this:
#Entity
#Table(name = "entities")
public class Entity {
...
private Date created;
private Date updated;
#PrePersist
protected void onCreate() {
created = new Date();
}
#PreUpdate
protected void onUpdate() {
updated = new Date();
}
}
or you can use the #EntityListener annotation on the class and place the event code in an external class.
You can just use #CreationTimestamp and #UpdateTimestamp:
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "create_date")
private Date createDate;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "modify_date")
private Date modifyDate;
Taking the resources in this post along with information taken left and right from different sources, I came with this elegant solution, create the following abstract class
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#MappedSuperclass
public abstract class AbstractTimestampEntity {
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created", nullable = false)
private Date created;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated", nullable = false)
private Date updated;
#PrePersist
protected void onCreate() {
updated = created = new Date();
}
#PreUpdate
protected void onUpdate() {
updated = new Date();
}
}
and have all your entities extend it, for instance:
#Entity
#Table(name = "campaign")
public class Campaign extends AbstractTimestampEntity implements Serializable {
...
}
What database column types you should use
Your first question was:
What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)? Will the data types be timezone-aware?
In MySQL, the TIMESTAMP column type does a shifting from the JDBC driver local time zone to the database timezone, but it can only store timestamps up to 2038-01-19 03:14:07.999999, so it's not the best choice for the future.
So, better to use DATETIME instead, which doesn't have this upper boundary limitation. However, DATETIME is not timezone aware. So, for this reason, it's best to use UTC on the database side and use the hibernate.jdbc.time_zone Hibernate property.
What entity property type you should use
Your second question was:
What data types would you use in Java (Date, Calendar, long, ...)?
On the Java side, you can use the Java 8 LocalDateTime. You can also use the legacy Date, but the Java 8 Date/Time types are better since they are immutable, and don't do a timezone shifting to local timezone when logging them.
Now, we can also answer this question:
What annotations would you use for the mapping (e.g. #Temporal)?
If you are using the LocalDateTime or java.sql.Timestamp to map a timestamp entity property, then you don't need to use #Temporal since HIbernate already knows that this property is to be saved as a JDBC Timestamp.
Only if you are using java.util.Date, you need to specify the #Temporal annotation, like this:
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_on")
private Date createdOn;
But, it's much better if you map it like this:
#Column(name = "created_on")
private LocalDateTime createdOn;
How to generate the audit column values
Your third question was:
Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?
What annotations would you use for the mapping (e.g. #Temporal)?
There are many ways you can achieve this goal. You can allow the database to do that..
For the create_on column, you could use a DEFAULT DDL constraint, like :
ALTER TABLE post
ADD CONSTRAINT created_on_default
DEFAULT CURRENT_TIMESTAMP() FOR created_on;
For the updated_on column, you could use a DB trigger to set the column value with CURRENT_TIMESTAMP() every time a given row is modified.
Or, use JPA or Hibernate to set those.
Let's assume you have the following database tables:
And, each table has columns like:
created_by
created_on
updated_by
updated_on
Using Hibernate #CreationTimestamp and #UpdateTimestamp annotations
Hibernate offers the #CreationTimestamp and #UpdateTimestamp annotations that can be used to map the created_on and updated_on columns.
You can use #MappedSuperclass to define a base class that will be extended by all entities:
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue
private Long id;
#Column(name = "created_on")
#CreationTimestamp
private LocalDateTime createdOn;
#Column(name = "created_by")
private String createdBy;
#Column(name = "updated_on")
#UpdateTimestamp
private LocalDateTime updatedOn;
#Column(name = "updated_by")
private String updatedBy;
//Getters and setters omitted for brevity
}
And, all entities will extend the BaseEntity, like this:
#Entity(name = "Post")
#Table(name = "post")
public class Post extend BaseEntity {
private String title;
#OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
#OneToOne(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.LAZY
)
private PostDetails details;
#ManyToMany
#JoinTable(
name = "post_tag",
joinColumns = #JoinColumn(
name = "post_id"
),
inverseJoinColumns = #JoinColumn(
name = "tag_id"
)
)
private List<Tag> tags = new ArrayList<>();
//Getters and setters omitted for brevity
}
However, even if the createdOn and updateOn properties are set by the Hibernate-specific #CreationTimestamp and #UpdateTimestamp annotations, the createdBy and updatedBy require registering an application callback, as illustrated by the following JPA solution.
Using JPA #EntityListeners
You can encapsulate the audit properties in an Embeddable:
#Embeddable
public class Audit {
#Column(name = "created_on")
private LocalDateTime createdOn;
#Column(name = "created_by")
private String createdBy;
#Column(name = "updated_on")
private LocalDateTime updatedOn;
#Column(name = "updated_by")
private String updatedBy;
//Getters and setters omitted for brevity
}
And, create an AuditListener to set the audit properties:
public class AuditListener {
#PrePersist
public void setCreatedOn(Auditable auditable) {
Audit audit = auditable.getAudit();
if(audit == null) {
audit = new Audit();
auditable.setAudit(audit);
}
audit.setCreatedOn(LocalDateTime.now());
audit.setCreatedBy(LoggedUser.get());
}
#PreUpdate
public void setUpdatedOn(Auditable auditable) {
Audit audit = auditable.getAudit();
audit.setUpdatedOn(LocalDateTime.now());
audit.setUpdatedBy(LoggedUser.get());
}
}
To register the AuditListener, you can use the #EntityListeners JPA annotation:
#Entity(name = "Post")
#Table(name = "post")
#EntityListeners(AuditListener.class)
public class Post implements Auditable {
#Id
private Long id;
#Embedded
private Audit audit;
private String title;
#OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
#OneToOne(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.LAZY
)
private PostDetails details;
#ManyToMany
#JoinTable(
name = "post_tag",
joinColumns = #JoinColumn(
name = "post_id"
),
inverseJoinColumns = #JoinColumn(
name = "tag_id"
)
)
private List<Tag> tags = new ArrayList<>();
//Getters and setters omitted for brevity
}
With Olivier's solution, during update statements you may run into:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'created' cannot be null
To solve this, add updatable=false to the #Column annotation of "created" attribute:
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created", nullable = false, updatable=false)
private Date created;
You can also use an interceptor to set the values
Create an interface called TimeStamped which your entities implement
public interface TimeStamped {
public Date getCreatedDate();
public void setCreatedDate(Date createdDate);
public Date getLastUpdated();
public void setLastUpdated(Date lastUpdatedDate);
}
Define the interceptor
public class TimeStampInterceptor extends EmptyInterceptor {
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState,
Object[] previousState, String[] propertyNames, Type[] types) {
if (entity instanceof TimeStamped) {
int indexOf = ArrayUtils.indexOf(propertyNames, "lastUpdated");
currentState[indexOf] = new Date();
return true;
}
return false;
}
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
if (entity instanceof TimeStamped) {
int indexOf = ArrayUtils.indexOf(propertyNames, "createdDate");
state[indexOf] = new Date();
return true;
}
return false;
}
}
And register it with the session factory
Thanks everyone who helped. After doing some research myself (I'm the guy who asked the question), here is what I found to make sense most:
Database column type: the timezone-agnostic number of milliseconds since 1970 represented as decimal(20) because 2^64 has 20 digits and disk space is cheap; let's be straightforward. Also, I will use neither DEFAULT CURRENT_TIMESTAMP, nor triggers. I want no magic in the DB.
Java field type: long. The Unix timestamp is well supported across various libs, long has no Y2038 problems, timestamp arithmetic is fast and easy (mainly operator < and operator +, assuming no days/months/years are involved in the calculations). And, most importantly, both primitive longs and java.lang.Longs are immutable—effectively passed by value—unlike java.util.Dates; I'd be really pissed off to find something like foo.getLastUpdate().setTime(System.currentTimeMillis()) when debugging somebody else's code.
The ORM framework should be responsible for filling in the data automatically.
I haven't tested this yet, but only looking at the docs I assume that #Temporal will do the job; not sure about whether I might use #Version for this purpose. #PrePersist and #PreUpdate are good alternatives to control that manually. Adding that to the layer supertype (common base class) for all entities, is a cute idea provided that you really want timestamping for all of your entities.
For those whose want created or modified user detail along with the time using JPA and Spring Data can follow this. You can add #CreatedDate,#LastModifiedDate,#CreatedBy and #LastModifiedBy in the base domain. Mark the base domain with #MappedSuperclass and #EntityListeners(AuditingEntityListener.class) like shown below:
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public class BaseDomain implements Serializable {
#CreatedDate
private Date createdOn;
#LastModifiedDate
private Date modifiedOn;
#CreatedBy
private String createdBy;
#LastModifiedBy
private String modifiedBy;
}
Since we marked the base domain with AuditingEntityListener we can tell JPA about currently logged in user. So we need to provide an implementation of AuditorAware and override getCurrentAuditor() method. And inside getCurrentAuditor() we need to return the currently authorized user Id.
public class AuditorAwareImpl implements AuditorAware<String> {
#Override
public Optional<String> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication == null ? Optional.empty() : Optional.ofNullable(authentication.getName());
}
}
In the above code if Optional is not working you may using Java 7 or older. In that case try changing Optional with String.
Now for enabling the above Audtior implementation use the code below
#Configuration
#EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JpaConfig {
#Bean
public AuditorAware<String> auditorAware() {
return new AuditorAwareImpl();
}
}
Now you can extend the BaseDomain class to all of your entity class where you want the created and modified date & time along with user Id
In case you are using the Session API the PrePersist and PreUpdate callbacks won't work according to this answer.
I am using Hibernate Session's persist() method in my code so the only way I could make this work was with the code below and following this blog post (also posted in the answer).
#MappedSuperclass
public abstract class AbstractTimestampEntity {
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created")
private Date created=new Date();
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated")
#Version
private Date updated;
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
Now there is also #CreatedDate and #LastModifiedDate annotations.
=> https://programmingmitra.blogspot.fr/2017/02/automatic-spring-data-jpa-auditing-saving-CreatedBy-createddate-lastmodifiedby-lastmodifieddate-automatically.html
(Spring framework)
If we are using #Transactional in our methods, #CreationTimestamp and #UpdateTimestamp will save the value in DB but will return null after using save(...).
In this situation, using saveAndFlush(...) did the trick
Following code worked for me.
package com.my.backend.models;
import java.util.Date;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import lombok.Getter;
import lombok.Setter;
#MappedSuperclass
#Getter #Setter
public class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
#CreationTimestamp
#ColumnDefault("CURRENT_TIMESTAMP")
protected Date createdAt;
#UpdateTimestamp
#ColumnDefault("CURRENT_TIMESTAMP")
protected Date updatedAt;
}
Just to reinforce: java.util.Calender is not for Timestamps. java.util.Date is for a moment in time, agnostic of regional things like timezones. Most database store things in this fashion (even if they appear not to; this is usually a timezone setting in the client software; the data is good)
A good approach is to have a common base class for all your entities. In this base class, you can have your id property if it is commonly named in all your entities (a common design), your creation and last update date properties.
For the creation date, you simply keep a java.util.Date property. Be sure, to always initialize it with new Date().
For the last update field, you can use a Timestamp property, you need to map it with #Version. With this Annotation the property will get updated automatically by Hibernate. Beware that Hibernate will also apply optimistic locking (it's a good thing).
As data type in JAVA I strongly recommend to use java.util.Date. I ran into pretty nasty timezone problems when using Calendar. See this Thread.
For setting the timestamps I would recommend using either an AOP approach or you could simply use Triggers on the table (actually this is the only thing that I ever find the use of triggers acceptable).
You might consider storing the time as a DateTime, and in UTC. I typically use DateTime instead of Timestamp because of the fact that MySql converts dates to UTC and back to local time when storing and retrieving the data. I'd rather keep any of that kind of logic in one place (Business layer). I'm sure there are other situations where using Timestamp is preferable though.
We had a similar situation. We were using Mysql 5.7.
CREATE TABLE my_table (
...
updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
This worked for us.
I think it is neater not doing this in Java code, you can simply set column default value in MySql table definition.

Spring Data update entity with yesterday's date

I have some problems with update (and also insert) data into my database. I have an entity with some integer properties, some String properties, but also is there one property with LocalDate type, and it has to be unique.
I put a lot of entities like that into the database, but user needs to edit it and update some properties. When I tried to test it and change some String property and save updated entity to db I saw this error log in the console:
Duplicate entry '2019-07-27' for key 'work_day_workday_date_uindex'
As you can see, Hibernate tries to put object with yesterday's date. But... why? I checked it in traditional ( :D ) way -> by entering System.out.println instruction before saving object into database.
Log shows me a correct date in printing:
WorkDay{id=296, date=2019-07-28, workingTime=8,....
So I think that the problem is connected with differences in time between database and application.
I found some tips here, in StackOverflow. Somebody said that removing serverTimezone=UTC from application.properties in SpringBoot could help. And it fixed the problem - yesterday I updated the entity successfully. But today I come back to coding and the problem appeared again.
I hope that maybe some of you had this problem in past and know some solution - it will be very helpful for me :)
Here is WorkDay Entity:
#Entity
#Table(name = "work_day")
public class WorkDay implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_workday")
private Long id;
#NotNull
#Column(name = "workday_date", nullable = false, unique = true)
private LocalDate date;
#NotNull
#Column(name = "working_time", nullable = false)
private Integer workingTime;
#Column(name = "booked_artist")
private String bookedArtist;
#ManyToOne
#JoinColumn(name="workday_importance_id")
private WorkDayImportance workDayImportance;
#ManyToMany
#JoinTable(name = "workday_employee",
joinColumns = {#JoinColumn(name = "workday_id",
referencedColumnName = "id_workday")},
inverseJoinColumns = {#JoinColumn(name="employee_id",
referencedColumnName = "id_employee")})
private List<Employee> employers;
#OneToMany(mappedBy = "workDay", cascade = CascadeType.REMOVE)
private List<Comment> comments;
Here is some code where I perform this operation:
public void setBookedArtist(Long workDayId, String artist){
workDayRepository
.findById(workDayId)
.ifPresent(workDay -> workDayDetailsService.saveBookedArtist(workDay, artist));
}
void saveBookedArtist(WorkDay workDay, String artist){
if(artist != null && !artist.equals("")) {
workDay.setBookedArtist(artist);
workDayRepository.save(workDay);
}
}
The entity repository is Spring Data interface which extends JpaRepository.
Best regards!
Setting the Id of workDay before saving the record should work and as we don't want to update the date set updatable = false as to below
public void setBookedArtist(Long workDayId, String artist){
workDayRepository
.findById(workDayId)
.ifPresent(workDay -> workDayDetailsService.saveBookedArtist(workDay, artist));
}
void saveBookedArtist(WorkDay workDay, String artist){
if(artist != null && !artist.equals("")) {
workDay.setId(workDay.getId());
workDay.setBookedArtist(artist);
workDayRepository.save(workDay);
}
}
#NotNull
#Column(name = "workday_date", nullable = false, unique = true, updatable = false)
private LocalDate date;

Spring JPA Hibernate CET timezone for AuditingEntityListener

I'm not succeeding at setting a CET timezone for my JPA application, which is using the AuditingEntityListener to augment creation/lastmodified dates.
Things I tried already:
In my application.properties (both combinations):
spring.jpa.properties.hibernate.jdbc.time_zone=UTC+1
spring.jpa.properties.hibernate.jdbc.time_zone=CET
Added timezone to my JDBC connection (both combinations)
spring.datasource.url=jdbc:mysql://host:3306/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC+1
spring.datasource.url=jdbc:mysql://host:3306/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=CET
Added a postconstruct (application level)
#PostConstruct
void started() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC+1"));
}
And also tried setting the timezone at database level using:
SET time_zone='+01:00';
No succeed whatsoever, Am I missing something?
Using the #createdDate as follows:
EDIT
#Data
#Builder
#Entity
#EntityListeners(AuditingEntityListener.class)
#NoArgsConstructor
#AllArgsConstructor
public class OrderHistoryRecord {
#Id
#GeneratedValue
#JsonIgnore
private Long id;
#NotNull
#ManyToOne(fetch = FetchType.LAZY, targetEntity = Order.class)
#JoinColumn(name = "order_id", updatable = false)
#JsonIgnore
private Order order;
#CreatedDate
private Date date;
#Enumerated(EnumType.STRING)
private PaymentStatus paymentStatus;
#Enumerated(EnumType.STRING)
private ShipmentStatus shipmentStatus;
#Enumerated(EnumType.STRING)
private OrderHistoryRecordType type;
}
I had the same issue and solved it by configuring a custom DateTimeProvider which uses UTC instead of the system timezone, see code below.
The mentioned solution to set the values manually feels not right to me because it mixes up the Spring JPA extension and the EntityListener support, why would you use JPA Auditing from Spring at all?
Solution for Spring Boot 1
#Configuration
#EnableJpaAuditing(dateTimeProviderRef = "utcDateTimeProvider")
public class JpaConfig {
#Bean
public DateTimeProvider utcDateTimeProvider() {
return () -> new GregorianCalendar(TimeZone.getTimeZone("UTC"));
}
}
Why Gregoriancalendar? Spring will convert the object of type GregorianCalendar to a LocalDateTime by using the converters Jsr310Converters.
Solution for Spring Boot 2
#Configuration
#EnableJpaAuditing(dateTimeProviderRef = "utcDateTimeProvider")
public class JpaConfig {
#Bean
public DateTimeProvider utcDateTimeProvider() {
return () -> Optional.of(LocalDateTime.now(ZoneOffset.UTC));
}
}
I hope it helps :)
You can use like this:
#CreatedDate
#Column(name = "created_date", nullable = false, updatable = false)
private LocalDateTime createdDate;
#LastModifiedDate
#Column(name = "last_modified_date")
private LocalDateTime lastModifiedDate;
#PrePersist
public void onCreate() {
this.createdDate = LocalDateTime.now(ZoneId.of("UTC"));
this.lastModifiedDate = LocalDateTime.now(ZoneId.of("UTC"));
}
#PreUpdate
public void onUpdate() {
this.lastModifiedDate = LocalDateTime.now(ZoneId.of("UTC"));
}
Spring internally called these annotation (#PrePersist and #PreUpdate before inserting or updating records resp.), You can override these annotation way to give your own implementation. Otherwise your database server time will get pick up. Changing time zone of java server won't help you.
Try "ECT" ?
Map<String, String> map = new HashMap<>(64);
map.put("ACT", "Australia/Darwin");
map.put("AET", "Australia/Sydney");
map.put("AGT", "America/Argentina/Buenos_Aires");
map.put("ART", "Africa/Cairo");
map.put("AST", "America/Anchorage");
map.put("BET", "America/Sao_Paulo");
map.put("BST", "Asia/Dhaka");
map.put("CAT", "Africa/Harare");
map.put("CNT", "America/St_Johns");
map.put("CST", "America/Chicago");
map.put("CTT", "Asia/Shanghai");
map.put("EAT", "Africa/Addis_Ababa");
map.put("ECT", "Europe/Paris");
map.put("IET", "America/Indiana/Indianapolis");
map.put("IST", "Asia/Kolkata");
map.put("JST", "Asia/Tokyo");
map.put("MIT", "Pacific/Apia");
map.put("NET", "Asia/Yerevan");
map.put("NST", "Pacific/Auckland");
map.put("PLT", "Asia/Karachi");
map.put("PNT", "America/Phoenix");
map.put("PRT", "America/Puerto_Rico");
map.put("PST", "America/Los_Angeles");
map.put("SST", "Pacific/Guadalcanal");
map.put("VST", "Asia/Ho_Chi_Minh");
map.put("EST", "-05:00");
map.put("MST", "-07:00");
map.put("HST", "-10:00");
SHORT_IDS = Collections.unmodifiableMap(map);
Adding configuration to application.properties works for Hibernate 5.2.3+. It is not clear which version you are using.
Another way to handle this is to set JVM parameter -Duser.timezone=CET in run configuration of your IDE or if you run the app from command line/script/docker etc.:
java -Duser.timezone=CET -jar your-jdbc-app.jar
Check if setting JVM timezone affects your use-cases.

Record's datetime is being set 3 hours backwards when update

I am developing a CRUD application in Spring boot and Hibernate. I have a table called Order. This table has two columns called status (integer) and datetime (which of type mysql datetime). In my application, I regulary update that status column's value in one of the rows.
When I do this, something weird happens. The status column is updated for that record, however, the datetime column is also being updated, which I don't even instruct. After each update to a row, datetime is set to 3 hours earlier than the previous value of its.
I am developing this application in Java's Spring Boot and Spring Boot JPA MySQL. I am using JPA repositories. Here is the snipped that makes the update:
public String incrementOrderStatus(Long orderId) {
Order order = orderRepository.findOne(orderId);
OrderState nextState = order.getState().next();
order.setState(nextState);
orderRepository.save(order);
return nextState.toString();
}
An Order has the following attributes:
#Data
#Entity
#Table(name = "`order`")
#NoArgsConstructor
#AllArgsConstructor
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false, updatable = false)
private Long id;
private String name;
private Calendar datetime;
#Enumerated(EnumType.ORDINAL)
private OrderState state;
private String address;
private String phoneNumber;
private String email;
#Enumerated(EnumType.ORDINAL)
private OrderSource source;
private Float totalPrice;
#ManyToOne(optional = true)
private Offer offerUsed;
private String notes;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "order", fetch = FetchType.LAZY)
private List<MealOrderDescriptor> meals;
public Order(CustomOrderView orderView) {
this.name = orderView.getName();
this.datetime = Calendar.getInstance(TimeZone.getTimeZone("Europe/Istanbul"));
this.state = OrderState.PENDING;
this.address = orderView.getAddress();
this.phoneNumber = orderView.getPhoneNumber();
this.source = orderView.getSource();
this.totalPrice = orderView.getTotalPrice();
this.notes = orderView.getNotes();
}
}
In the JDBC query string I also set the timezone to my timezone, which is serverTimezone=Europe/Istanbul. I am using a MySQL version of 5.7.19 and JDBC version is 6.0.6, Java 1.8 and Spring Boot 1.5.9 and in an Ubuntu 16.04.3
Thanks in advance.
Even though you don't call order.setDatetime() before orderRepository.save(order);, datetime field contains value received by orderRepository.findOne(orderId).
After that, orderRepository.save(order); statement tries to update datetime field with the value received by orderRepository.findOne(orderId). If it is minus 3 hours from the previous value then it is likely a TimeZone problem.
I think, if you use TIMESTAMP type instead of DATETIME this situation will disappear. Because MySQL DATETIME type does not hold TimeZone information.
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)
You can check official documentation.

Spring-Data-Jpa AuditingEntityListener createdDate updated upon saving existing entity

I have the following JPA Entity:
#EntityListeners(AuditingEntityListener.class)
#Entity
public class EntityWithAuditingDates {
#Id
#GeneratedValue
private Long id;
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date createdDate;
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date lastModified;
private String property;
// getters and setters omitted.
}
And the following CrudRepository:
#Service
public interface EntityWithAuditingDatesRepository extends CrudRepository<EntityWithAuditingDates, Long> {
}
And the following test:
#SpringApplicationConfiguration(classes = FooApp.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class AuditingEntityListenerTest {
#Autowired
private EntityWithAuditingDatesRepository entityWithAuditingDatesRepository;
#Test
public void test() {
EntityWithAuditingDates entityWithAuditingDates = new EntityWithAuditingDates();
entityWithAuditingDates.setProperty("foo");
assertNull(entityWithAuditingDates.getCreatedDate());
assertNull(entityWithAuditingDates.getLastModified());
entityWithAuditingDatesRepository.save(entityWithAuditingDates);
assertNotNull(entityWithAuditingDates.getCreatedDate());
assertNotNull(entityWithAuditingDates.getLastModified());
assertEquals(entityWithAuditingDates.getLastModified(), entityWithAuditingDates.getCreatedDate());
entityWithAuditingDates.setProperty("foooo");
entityWithAuditingDatesRepository.save(entityWithAuditingDates);
assertNotEquals(entityWithAuditingDates.getCreatedDate(), entityWithAuditingDates.getLastModified());
}
}
The last condition fails. Shouldn't be the createdDate and the lastModifiedDate be different after updating the entity?
Thanks!
I faced the same issue but figured out a workaround for now. On #Column, I have set updatable=false to exclude create* fields on update.
#CreatedBy
#NotNull
#Column(name = "created_by", nullable = false, length = 50, updatable = false)
private String createdBy;
#CreatedDate
#NotNull
#Column(name = "created_date", nullable = false, updatable = false)
private ZonedDateTime createdDate = ZonedDateTime.now();
#LastModifiedBy
#Column(name = "last_modified_by", length = 50)
private String lastModifiedBy;
#LastModifiedDate
#Column(name = "last_modified_date")
private ZonedDateTime lastModifiedDate = ZonedDateTime.now();
It's not necessary to do another query to see fields updated. The repository's save method returns an object, which the documentation says that you should always use for further operations. The returned object should pass that last assertion. Try this:
entityWithAuditingDates = entityWithAuditingDatesRepository.save(entityWithAuditingDates);
If you retrieve the entity from the database after the update operation, the fields are set correctly. The test case below passes. Still, I wonder why they are set correctly on the first save operation, but then incorrectly upon the second. And you only get the correct information in the end when you retrieve the record from the database. I guess this is related to the hibernate cache.
#Test
public void test() throws InterruptedException {
EntityWithAuditingDates entityWithAuditingDates = new EntityWithAuditingDates();
entityWithAuditingDates.setProperty("foo");
assertNull(entityWithAuditingDates.getCreatedDate());
assertNull(entityWithAuditingDates.getLastModified());
entityWithAuditingDatesRepository.save(entityWithAuditingDates);
assertNotNull(entityWithAuditingDates.getCreatedDate());
assertNotNull(entityWithAuditingDates.getLastModified());
assertEquals(entityWithAuditingDates.getLastModified(), entityWithAuditingDates.getCreatedDate());
entityWithAuditingDates.setProperty("foooo");
Thread.sleep(1000);
entityWithAuditingDatesRepository.save(entityWithAuditingDates);
EntityWithAuditingDates retrieved = entityWithAuditingDatesRepository.findOne(entityWithAuditingDates.getId());
assertNotNull(retrieved.getCreatedDate());
assertNotNull(retrieved.getLastModified());
assertNotEquals(retrieved.getCreatedDate(), retrieved.getLastModified());
}

Categories

Resources