简体   繁体   中英

JPA CreateNativeQuery returns wrong date

We recently updated a project from using Hibernate 4 to Hibernate 5.2, and with that came the need to update all of our Criteria to use JPA. For the most part things are in working order, but I have one query that is no longer behaving. One of the fields on the table we are querying is of type DATE in the database.

When I query directly on the table I get back the date- say it is "2017-04-20." However, when I run the same query on our development server, using JPA's createNativeQuery, I get back the date "2017-04-19"

I don't think this is an issue with the query as I run the exact same query both through a mysql terminal and through java and get different results. The query that I run is the one that is logged in my below example. I think it may be a timezone issue as I don't have this problem on my local environment, just on my dev server, but it also wasn't a problem until we updated to the new versions of Hibernate.

public List<ResponseDTO> getDashboardData(String date, Integer page, Integer pageSize, AbstractDashboard dashboard) {
    List<ResponseDTO> processed = new ArrayList<ResponseDTO>();
    String query = getDashboardQuery(date, dashboard);
    logger.info("Dashboard Query: " + query);
    List<Object[]> raw = createNativeQuery(query).getResultList();

    return raw.stream().map(r->new ResponseDTO(r)).collect(Collectors.toList());
}

And the constructor of my DTO object:

public ResponseDTO(Object[] r) {
    this.date = ((Date) r[0]).toLocalDate();
    System.out.println(this.date.toString());//This date does not match what is in the db.

    this.type = (String) r[1];
    this.label = (String) r[2];
    this.value = (Double) r[3];
}

Edit:

I think it's actually an issue with the java.sql.Date type, because I tried printing that out on my dev server and it also returns "2017-04-19" instead of the 20th. I don't get why this doesn't match the results when I run the query in a mysql console, it seems like they should be the same to me.

Try another JDBC driver

Ok, I got it working. For what it's worth, this seems like complete madness to me. The "Aha!" moment came while reading this answer to a different question.

Since it is the mysql driver that dictates how the date is parsed in the system. I rolled back my mysql driver as that was one of the packages that I updated. Suddenly everything behaved as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM