簡體   English   中英

Java,Spring:在為java.sql.Timestamp添加時區之后,查找給定時間范圍內的對象無法正常工作

[英]Java, Spring : Finding objects within a given time-frame not working after adding time-zone to java.sql.Timestamp

我正在開發一個Spring-MVC項目,其中我有一個GroupNotes對象,我試圖在給定的時間范圍內搜索以通知用戶。 時間最初保存在Timestamp object without timezone Postgresql Timestamp object without timezone 后來我們為它添加了時區。 但由於我們已經這樣做了,我們找不到任何對象,DAO代碼無效。 我們修改了PostgreSQL列以及用於遷移到時區的模型定義。

DAO代碼:

@Override
    public List<GroupNotes> findGroupNotesWithExpiryInTwelveHours() {
        Session session = this.sessionFactory.getCurrentSession();
        long currentTime = System.currentTimeMillis();
        long plus47Hours = currentTime + (11 * 60 * 60 * 1000);
        Timestamp plus47HoursTS = new Timestamp(plus47Hours);

        long plus48Hours = currentTime + (12 * 60 * 60 * 1000);
        Timestamp plus48HoursTS = new Timestamp(plus48Hours);

        Query query = session.createQuery("from GroupNotes as gn where gn.zugwisenPersonId!=:val and gn.noteTarget > :from and gn.noteTarget < :to");
        query.setParameter("val", 0);
        query.setParameter("from", plus47HoursTS);
        query.setParameter("to", plus48HoursTS);
        return query.list();
    }

GroupNotes對象:

@Entity
@Table(name = "groupnotes")
public class GroupNotes implements Serializable {

    private static final long serialVersionUID = 1L;


    @Column(name = "notetarget",columnDefinition = "timestamp with time zone")
    private java.sql.Timestamp noteTarget;

// Other columns
}

調用代碼的服務層方法:

//此外,有人可以告訴我,如果下面的腳本每2小時執行一次嗎?

  @Override
    @Scheduled(cron = "0 0 0/2 * * *")
    public void checkForZugweisedNotesAndSendEmail() {

  List<GroupNotes> twelveHourList = this.groupNotesService.findGroupNotesWithExpiryInTwelveHours();
            for (GroupNotes groupNotes : twelveHourList) {
// Perform operations
}

我不明白為什么你要用硬路。我相信你已經把你的postgre方面的數據類型更改為timestamp 。所以你只需要改變你這樣的實體

@Column(name = "notetarget",columnDefinition = "timestamp with time zone")
@Temporal(TemporalType.TIMESTAMP)//declare timestamp
private Date noteTarget;//no need to use java.sql.Timestamp

在您的方法中,只需使用日期並相應地設置特定時間

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,11);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date plus47Hours  = cal.getTime();

然后您可以簡單地更改您的查詢

from GroupNotes as gn where gn.zugwisenPersonId!=:val and gn.noteTarget between :from and :to

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM