Issue
I have two entities in two different services and two different databases and both of them have one DateTime column in common
when I want to set an exact time for both columns, in one of the services the time is right but in another one time is set for two hours ago
Save Query in first entity ( wrong time ) :
@Modifying
@Query(value = "UPDATE PlatformOrganization p SET p.paymentsMatchingLastUpdate = :time WHERE p.externalUUID = :organizationExternalUUID")
void updatePaymentsMatchingLastUpdateByExternalUUID(@Param("organizationExternalUUID") String organizationExternalUUID, @Param("time") LocalDateTime time);
save Query in second entity ( right time ) :
public PlatformResponse<ImportConfigurationDto> updateConfigurationPaymentsMatchingLastUpdate(LocalDateTime updateTime, String externalUUID) {
ImportConfiguration configuration = importConfigurationDao.findByExternalUUID(externalUUID);
if (configuration == null)
return new PlatformResponse<>("configuration not found");
configuration.setPaymentsMatchingLastUpdate(updateTime);
importConfigurationDao.save(configuration);
return new PlatformResponse<>(mapper.mapToDto(configuration));
}
Solution
I don't know what kind of Datetime
you store in Database and Datetime
you define in DTO Object.
Can you share more about it?
In case you use Spring Boot. Config in properties
file to give you more info:
# Show SQL Query
spring.jpa.show-sql=true
# Show Binding
logging.level.org.hibernate.type.descriptor.sql=trace
# Show details patch and transaction
logging.level.ROOT=INFO
logging.level.org.hibernate.engine.transaction.internal.TransactionImpl=DEBUG
logging.level.org.springframework.orm.jpa=DEBUG
logging.level.org.springframework.transaction=DEBUG
I think the issue because the converter in @Query If use spring you can use:
@Component
@Converter(autoApply = true)
public class DateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) {
if (localDateTime == null) {
return null;
}
return Timestamp.from(ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toInstant());
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp.getTime()),
ZoneId.systemDefault());
}
}
Answered By - Duc Vo
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)