2013-03-24 74 views
2

我使用休眠4.1.10在我的Java控制檯應用程序,我已經得到了與下面列型號:Java的休眠從MySQL日期時間截斷一部分時間在閱讀

@Column(name = "created_at", columnDefinition="datetime") 
@Temporal(TemporalType.TIMESTAMP) 
private Date createdAt; 

我只是希望Java處理整個MySQL日期時間正確。現在,它只能讀取日期部分,其餘部分被截斷。我有一個簡單的測試,我只打印getCreatedAt()屬性到stdout:

System.out.println(income.getCreatedAt()); 

,並打印出以下幾點:

2012-05-11 00:00:00.0 
2012-05-29 00:00:00.0 
2012-05-30 00:00:00.0 
2012-06-28 00:00:00.0 
2012-07-30 00:00:00.0 
2012-08-29 00:00:00.0 
2012-09-28 00:00:00.0 
2012-10-30 00:00:00.0 
2012-11-29 00:00:00.0 
2012-12-02 00:00:00.0 
2012-12-21 00:00:00.0 
2012-12-24 00:00:00.0 
2013-01-30 00:00:00.0 
2013-02-27 00:00:00.0 
2013-02-27 00:00:00.0 

這是我show create table爲表:

CREATE TABLE `category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT, 
`parent_id` bigint(20) DEFAULT NULL, 
`name` varchar(32) NOT NULL, 
`type` varchar(255) DEFAULT NULL, 
`created_at` datetime NOT NULL, 
`updated_at` datetime NOT NULL, 
`created_by` bigint(20) DEFAULT NULL, 
`updated_by` bigint(20) DEFAULT NULL, 
PRIMARY KEY (`id`), 
KEY `category_type_idx` (`type`), 
KEY `created_by_idx` (`created_by`), 
KEY `updated_by_idx` (`updated_by`), 
KEY `category_parent_id_category_id` (`parent_id`), 
CONSTRAINT `category_created_by_sf_guard_user_id` FOREIGN KEY (`created_by`) REFERENCES `sf_guard_user` (`id`), 
CONSTRAINT `category_parent_id_category_id` FOREIGN KEY (`parent_id`) REFERENCES `category` (`id`), 
CONSTRAINT `category_updated_by_sf_guard_user_id` FOREIGN KEY (`updated_by`) REFERENCES `sf_guard_user` (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8 

我一直在試圖遵循網上找到的幾個tuts/answers(也在stackoverflow上),並決定使用java.util.Date和annotation來代替java.sql.Date(因爲MySQL類型是datetime)。這是我所能達到的。我能做些什麼來檢索時間部分?

回答

2

您可能數據庫中的數據已被截斷。嘗試存儲Timestamp而不是Date。例如

@Column(name = "created_at", length = 19) 
public Timestamp getCreatedAt() { 
    return this.createdAt; 
} 

setCreatedAt(new Timestamp(Calendar.getInstance().getTimeInMillis())); 
+1

起初,我無法相信你寫的內容,但最終你是對的。數據已被截斷。謝謝! – ducin 2013-03-27 22:13:18