java Hibernate 映射 MySQL DateTime
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15389084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate mapping MySQL DateTime
提问by displayName
I've a table in a mysql db with the following schema: [ID, Value, Date] where ID and Value are int field and Date is a TIMESTAMP. I defined a Java class like this:
我在 mysql 数据库中有一个表,其架构如下: [ID, Value, Date] 其中 ID 和 Value 是 int 字段,Date 是时间戳。我定义了一个这样的 Java 类:
class myClass{
private int ID;
private int value;
private java.sql.Timestamp date;
}
If I try to read records from the db using the map that I defined for Hibernate everything looks good, anyway if I create a new object and I try to insert it in my db I get errors. I read a lot of post about this but I'm really confused.
如果我尝试使用我为 Hibernate 定义的映射从 db 读取记录,一切看起来都不错,无论如何,如果我创建一个新对象并尝试将它插入我的 db 中,我会收到错误消息。我读了很多关于这个的帖子,但我真的很困惑。
回答by javadev
Use the java.util.Date class instead of java.sql.Date. Then it should look like this :
使用 java.util.Date 类而不是 java.sql.Date。然后它应该是这样的:
public class myClass {
private int ID;
private int value;
@Temporal(TemporalType.TIMESTAMP)
private java.util.date date;
}
回答by WPrecht
You need to tell Hibernate (or JPA) what the column is. Different databases handle naked date fields differently. I know in Oracle, if you don't annotate the column, Oracle will make it an (Oracle) timestamp. Which may or may not be what you want and what it won't be is performant. I'd recommend always using an annotation and based on this question, it looks like you have to with mySQL.
您需要告诉 Hibernate(或 JPA)列是什么。不同的数据库以不同的方式处理裸日期字段。我知道在 Oracle 中,如果您不对该列进行注释,Oracle 会将其设为 (Oracle) 时间戳。这可能是也可能不是您想要的,而它不会是高性能的。我建议始终使用注释,并且基于这个问题,看起来您必须使用 mySQL。
Try this:
试试这个:
class myClass {
private int ID;
private int value;
@Temporal(TemporalType.TIMESTAMP)
private java.sql.Timestamp date;
}