【问题标题】:Current datetime in Joda-Time date formatting for mysql timestampmysql时间戳的Joda-Time日期格式中的当前日期时间
【发布时间】:2014-01-04 16:20:43
【问题描述】:

我需要将当前日期和时间导入到格式为TimeStamp 的MySQL 数据库字段中。通过检查示例数据,MySQL TimeStamp 数据类型的格式似乎是“yyyy-mm-dd hh:mm:ss”。我在我的 spring hibernate 应用程序中使用Joda-Time 格式。如何以底层 MySQL TimeStamp 格式字段接受的格式获取当前日期时间?

这是我当前的代码,它不会编译,因为 eclipse 说 .parseDateTime() 需要一个字符串参数而不是 DateTime 参数:

public void setCreated(){
    DateTime now = new org.joda.time.DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss");
    created = fmt.parseDateTime(now);
    System.out.println("'''''''''''''''''''''' created is: "+created);
}

我试图坚持的实体定义如下:

@Entity
@Table(name = "documents")
public class Document {
@Id
@GeneratedValue
@Column(name="id")
private Integer id;

@ManyToOne
@JoinColumn(name = "client_id")
private Patient patient;

@ManyToOne
@JoinColumn(name = "type_id")
private DocumentType type;

@Column(name="name")
private String name;

@Column(name="description")
private String description;

@Column(name="filename")
private String filename;

@Column(name="content")
@Lob
private Blob content;

@Column(name="content_type")
private String contentType;

@Column(name = "created")
private DateTime created;

public Integer getId(){return id;}
public void setId(Integer i){id=i;}

protected void setPatient(Patient patient) {this.patient = patient;}
public Patient getPatient(){return this.patient;}

public void setType(DocumentType type) {this.type = type;}
public DocumentType getType() {return this.type;}

public String getName(){return name;}
public void setName(String nm){name=nm;}

public String getDescription(){return description;}
public void setDescription(String desc){description=desc;}

public String getFileName(){return filename;}
public void setFileName(String fn){filename=fn;}

public Blob getContent(){return content;}
public void setContent(Blob ct){content=ct;}

public String getContentType(){return contentType;}
public void setContentType(String ctype){contentType=ctype;}

public void setCreated(){
    DateTime now = new org.joda.time.DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss");
    created = fmt.parseDateTime(now);
System.out.println("''''''''''''''''''''''''''' created is: "+created);
}
public DateTime getCreated() {return this.created;}

@Override
public String toString() {return this.getName();}
public boolean isNew() {return (this.id == null);}

}

如何更改上述内容,以便以正确的格式保存数据以插入 MySQL 时间戳字段?


编辑:

与 Sotirios 的建议有关,这里是我当前 pom.xml 的相关部分,以供讨论:

<properties>
    <jodatime-hibernate.version>1.3</jodatime-hibernate.version>
    <jodatime-jsptags.version>1.1.1</jodatime-jsptags.version>
    <jodatime.version>2.3</jodatime.version>
    <jadira-usertype-core.version>3.1.0.CR8</jadira-usertype-core.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.jadira.usertype</groupId>
        <artifactId>usertype.core</artifactId>
        <version>${jadira-usertype-core.version}</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>${jodatime.version}</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time-hibernate</artifactId>
        <version>${jodatime-hibernate.version}</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time-jsptags</artifactId>
        <version>${jodatime-jsptags.version}</version>
    </dependency>
</dependencies>

【问题讨论】:

  • 你是直接使用JDBC吗?
  • @SotiriosDelimanolis 我正在使用hibernate和jpa。
  • 你必须向我们展示你试图坚持的实体。
  • @SotiriosDelimanolis 我刚刚为上面的实体添加了代码。你还需要什么吗?
  • 这个我不详细了解,但是Hibernate必须对Joda有一些支持。也许开始here

标签: java mysql spring spring-mvc jodatime


【解决方案1】:

因为您似乎需要它:

我的实体类

@Entity
@Table(name = "time_fields")
public class TimeFields {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long timeId;

    @Column
    @Temporal(TemporalType.DATE)
    private Date date;

    @Column
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime dateTime;

使用适当的 getter 和 setter。

客户端代码

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PersistenceContext.class);
SessionFactory sessionFactory = context.getBean(SessionFactory.class);
Session session = sessionFactory.openSession();

TimeFields timeFields = new TimeFields();
Date date = new Date();
DateTime dateTime = new DateTime();
System.out.println(date);
System.out.println(dateTime);
timeFields.setDate(date);
timeFields.setDateTime(dateTime);

session.beginTransaction();
session.persist(timeFields);
session.getTransaction().commit();

System.out.println(timeFields.getTimeId());
System.out.println(timeFields.getDate());
System.out.println(timeFields.getDateTime());

打印出来

Tue Dec 17 00:22:35 EST 2013
2013-12-17T00:22:35.843-05:00
3
Tue Dec 17 00:22:35 EST 2013
2013-12-17T00:22:35.843-05:00

除了 joda-time 和 hibernate,您还需要 jadira 库

<dependency>
    <groupId>org.jadira.usertype</groupId>
    <artifactId>usertype.jodatime</artifactId>
    <version>2.0.1</version>
</dependency>

您应该阅读有关 Hibernate 的更多信息UserTypes。

【讨论】:

  • @CodeMed 忘记您可能在控制台中看到的 MySQL 时间戳格式。这只是一个显示,它与实际存储的内容无关(它确实如此,但它只是一个表示)。使用上面的代码可以很好地存储数据。
  • @CodeMed 如果您指的是format as what you enter in the console to insert a row,那么在使用 JDBC 时也要忘记这一点。您不会在 JDBC 中插入带有字符串的日期。您使用setDatesetTimesetTimeStamp 方法。
【解决方案2】:

日期的字符串表示纯粹供人类使用。时间戳在内部表示为与时区无关的数值。由于yyyy-mm-dd hh:mm:ss 不包含时区,因此尝试自己进行转换会使您遇到时区错误。

Hibernate 将直接处理 java.util.Datejava.sql.Date,因此您可以将数据类型更改为其中之一,然后在 getter/setter 中执行到 joda 对象的映射,这样它对调用者可用。

最好,IMO,您可以为 Hibernate 提供到 joda 对象的映射。已经为此准备了一个库:

https://github.com/JodaOrg/joda-time-hibernate

或通过 Maven:

http://mvnrepository.com/artifact/joda-time/joda-time-hibernate

注意:我个人的经验法则是,如果您看到将日期操作为字符串的代码,它就会被破坏......无论如何都不是科学指标,但我发现它比 50/50 好得多。 :)

编辑:文档在这里:http://www.joda.org/joda-time-hibernate/userguide.html

在类路径中,您应该能够像这样注释您的列:

@Column(name = "created")
@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
private DateTime created;

【讨论】:

  • 链接也添加到文档中。如果您选择更改休眠配置的路线,您的代码应该可以按原样运行。
  • 通常,getX 或 setX 只是值的传递方法。例如public DateTime getCreated() { return created; } 如果要将其设置为当前时间,只需将created 分配给您上面给now 的值即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 2012-01-03
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2014-07-07
  • 2013-03-10
相关资源
最近更新 更多