2014-12-04 33 views
0

我有一個問題與使用Java 休眠與MySQL的存儲列屬性休眠轉換的Java日期到MySQL YEAR

MySQL表:

CREATE TABLE DateTest (
    id INT NOT NULL AUTO_INCREMENT, 
    year YEAR(4), 
    PRIMARY KEY(id) 
) ENGINE = InnoDB; 

..

Java訪問類

public class DateTest implements java.io.Serializable { 

    private Integer id; 
    private Date year; 

    public DateTest() { 
    } 

    public DateTest(Date year) { 
     this.year = year; 
    } 


    public Integer getId(){ 
     return this.id; 
    } 

    public void setId(Integer id){ 
     this.id = id; 
    } 

    public Date getYear(){ 
     return this.year; 
    } 

    public void setYear(Date year){ 
     this.year = year; 
    } 

} 

Java代碼來保存記錄

DateTestDao tcd = new DateTestDao(); 
Date dd = new Date(); 

DateTest dt = new DateTest(); 
tc.setYear(dd); 
tcd.saveRecord(dt); 

當我想用Hibernate的session.save出現以下錯誤:

錯誤org.hibernate.util.JDBCExceptionReporter - 數據截斷「年」列在第1行

Prinicpally,我知道它爲什麼會發生,因爲該日期元素較大比允許的年份屬性,但我不知道如何解決它。

最好的問候, 邁克爾

回答

0

,難道你不想寫全日對象爲當年場?你應該使用getYear從寫入this.year之前的日期讀取年份(並且不要忘記增加1900,因爲你可能需要整整一年,而不僅僅是1900年)。

public void setYear(Date year){ 
    this.year = year.getYear() + 1900; 
} 

注意:您可能會考慮使用Calendar類,因爲大多數Date方法似乎過時了。