Fetching/selecting bottom N elements is messing up the value of time stamp in result set (because of time zone I think)

徘徊边缘 提交于 2020-06-17 09:34:51

问题


I spent almost a day trying to fetch bottom 10 rows from a table that has few hundred thousand rows in multiple ways. But timestamp in result set is always messed up by 7 hours (that is the time difference between UTC and my local)

Schema

CREATE TABLE IF NOT EXISTS xyz(
  id timestamp NOT NULL, 
  name varchar(40) NOT NULL, 
  PRIMARY KEY (id,name )
);

Bottom 10 entries in db after running select * from xyz order by id desc limit 10;

 2020-05-12 12:00:00+00  
 2020-05-12 12:00:00+00  
 2020-05-12 11:59:00+00  
 2020-05-12 11:58:00+00  
 2020-05-12 11:58:00+00  
 2020-05-12 11:58:00+00  
 2020-05-12 11:57:00+00  
 2020-05-12 11:56:00+00  
 2020-05-12 11:56:00+00  
 2020-05-12 11:55:00+00

I tried following 3 ways of selecting bottom 10 rows from DB. Also I always get null list if I select within a range.

List<xyz> findTop10ByOrderByIdDesc();
List<xyz> findTop10DistinctByIdBetweenOrderByIdDesc(LocalDateTime now,LocalDateTime after);
List<xyz> findTop10DistinctByIdBetweenOrderByIdDesc(Date now,Date after);

Here is POJO for holding the result set of above query

public class xyz{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private java.util.Date id;
//private LocalDateTime id
  private String name;

// ...
}

but id field is always off by 7 hours (for example: 1st element I get is 2020-05-12 05:00:00) . a)How can I fix my code to get right timestamp in POJO (or result set). b) How can I retrieve all the entries within a range (I get null list now). I think both of them are related


回答1:


java.util.Date which technically according to the documentation represents a point in time. But in reality it is a an awful mixture that gets used for all kinds of stuff. This results in all kind of weird (and probably plain wrong) stuff happening in the database, the driver and any ORM layers on top of that.

Luckily java.util.Date now hasa proper replacement in the java.time.* package. You are seem to be interested in a point of time: When did an event happen. The correct data type for that is [Instant][1].

While I can't promise anything the chances of that being persisted and loaded in the correct way is much bigger.



来源:https://stackoverflow.com/questions/61810380/fetching-selecting-bottom-n-elements-is-messing-up-the-value-of-time-stamp-in-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!