【问题标题】:Hibernate Conversion Java Date to MySQL YEARHibernate 将 Java 日期转换为 MySQL YEAR
【发布时间】:2014-12-04 13:55:28
【问题描述】:

我在使用 Java Hibernate 存储具有 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);

当我想使用 Hibernates session.save 时出现以下错误:

错误 org.hibernate.util.JDBCExceptionReporter - 第 1 行的“年份”列的数据被截断

基本上,我知道为什么会发生,因为日期元素大于允许的年份属性,但我不知道如何解决。

最好的问候, 迈克尔

【问题讨论】:

    标签: java mysql hibernate


    【解决方案1】:

    您不是想将整个日期对象写入年份字段吗?在写入this.year 之前,您应该使用getYear 从日期读取年份(并且不要忘记添加1900,因为您可能需要整年,而不仅仅是1900 年)。

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

    注意:您可能会考虑使用 Calendar 类,因为大多数 Date 方法似乎已被弃用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 2021-10-05
      • 1970-01-01
      相关资源
      最近更新 更多