gpt4 book ai didi

java - Hibernate insert or update datetime mysql always get 12 :00:00 or 00:00:00

转载 作者:行者123 更新时间:2023-11-29 05:52:06 25 4
gpt4 key购买 nike

我是 hibernate 新手

我用hibernate和struts2写了一个小应用

我的问题是

当我更新日期时间时,我的时间将是 00:00:00 或 12:00:00,它与我选择的 04:50:10 或 18:20:11 不正确

试了很多次还是不行

在我的表单中,我有一个字段是字符串,然后我将它转换成日期,然后用 hibernate 更新它

我的转换代码

public Date convertStringToDate(String str) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
try {
date = formatter.parse(str);
} catch (ParseException ex) {
Logger.getLogger(NewsAdminAction.class.getName()).log(Level.SEVERE, null, ex);
}
return date;
}

public String convertDateToString(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
String str = formatter.format(date);
return str;
}

我的更新代码 hibernate

//create session begin transaction

String sqlNoThumb = "UPDATE News set title = :title, info = :info, publicdate = :publicdate, active = :active, titleviet = :titleviet where idnews = :idnews";

Query query = session.createQuery(sqlNoThumb);
query.setString("title", news.getTitle());
query.setString("info", news.getInfo());
query.setDate("publicdate", news.getPublicdate());
query.setInteger("active", news.getActive());
query.setString("titleviet", news.getTitleviet());
query.setInteger("idnews", news.getIdnews());
result = query.executeUpdate();

最佳答案

您需要使用 java.sql.Timestamp,而不是 java.sql.Date

From the JavaDocs :

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero

关于java - Hibernate insert or update datetime mysql always get 12 :00:00 or 00:00:00,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13492775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com