简体   繁体   English

Java中的日期时间和休眠中的默认日期时间映射

[英]Datetime in java and default datetime mapping in hibernate

I need some little help about a confusion i'm having. 我需要一些有关混乱的小帮助。 since i came from C# .NET i was expeting java to have something similar to C# DateTime. 由于我来自C#.NET,因此我尝试让Java具有类似于C#DateTime的功能。 While i manage to create a helper method to convert string representation of date like eg "2009-10-16 11:14:34" to date object. 虽然我设法创建一个辅助方法来将日期的字符串表示形式(例如“ 2009-10-16 11:14:34”)转换为日期对象。 here is the method 这是方法

  public static Date convertToDateTime(String stringDate) { 
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date;
    try {
        date = df.parse(stringDate);
    } catch(ParseException e){
        e.printStackTrace();
    }
    return date;
 }

now i just want to persist now (i mean now date, like actual date) like New Date() and have that date in the database have the same representation yyyy-MM-dd HH:mm:s. 现在,我只想像New Date()这样立即保留(我的意思是现在的日期,如实际的日期),并在数据库中将该日期具有相同的表示形式yyyy-MM-dd HH:mm:s。 Unless i'm not getting something fundamental 除非我没有基本的东西

Since i'm using hibernate is it due to the mapping file? 由于我正在使用休眠,是由于映射文件吗? if so i have 2 question 1 How to then map my property so that New Date will be persited in this format yyyy-MM-dd HH:mm:s 2 How to have a default datetime mapping so if the property is null it still will be persited in the yyyy-MM-dd HH:mm:s format Thanks for reading 如果是这样,我有2个问题1如何然后映射我的属性,以便将新日期以这种格式进行保存yyyy-MM-dd HH:mm:s 2如何具有默认的日期时间映射,因此,如果属性为null,它仍然会请以yyyy-MM-dd HH:mm:s格式保存

You don't want your dates being stored in any format, you want them to be stored as a date. 您不希望日期以任何格式存储,而是希望将日期存储为日期。

This mapping definition could work (not sure about the default=now() part): 该映射定义可以工作(不确定default=now()部分):

<property name="foo" not-null="false">
    <column name="foo" default="now()" not-null="true" sql-type="datetime" />
</property>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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