【问题标题】:Hibernate returns null for time '00:00:00'Hibernate 在“00:00:00”时间返回 null
【发布时间】:2020-08-31 00:51:00
【问题描述】:

我正在将 Spring Hibernate 用于 Web 应用程序。它有一个OpenHours 模式,返回开放时间。它有一个字段sundayOpentype="time"。只要数据库列“sundayOpen”中的时间等于“00:00:00”,sundayOpen 就会返回 null。但所有其他时间它都会返回正确的时间。 我在使用 hibernate 5.4.2 和 3.6.0 时遇到过这个问题。

有什么方法可以得到 '00:00:00' 而不是 null

OpenHours.hbm.xml

<class name="com.example.OpenHours" table="openHours" schema="abxd_db">
        <id name="id" type="long">
            <column name="id"/>
            <generator class="assigned"/>
        </id> 
        <property name="sundayOpen" type="time">
            <column length="16" name="sundayOpen"/>
        </property>
</class>

OpenHours.java

 public class OpenHours implements Serializable {

    private long id;
     private Time sundayOpen; 

    @Id
    @Column(name = "id", nullable = false)
    public long getId() {
        return id;
    }

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

    public Time getSundayOpen() {
        return sundayOpen;
    }

    public void setSundayOpen(Time sundayOpen) {
        this.sundayOpen = sundayOpen;
    } 
}

【问题讨论】:

    标签: java mysql spring hibernate hibernate-mapping


    【解决方案1】:

    您可以创建自定义UserType

    public class CustomTimeUserType implements UserType {
        public void nullSafeSet(PreparedStatement ps, Object value, int index) throws HibernateException, SQLException {
            if (value == null)
                ps.setString(index, "00:00:00");
            else
                ps.setDate(index, (Time) value);
        }
       // implement other methods
    
    }
    

    并在属性中使用它,

    <property name="sundayOpen" type="time">
        <column length="16" name="com.pkg.CustomTimeUserType"/>
    </property>
    

    我不确定,但你也可以试试zeroDateTimeBehavior

    hibernate.connection.zeroDateTimeBehavior=round
    

    【讨论】:

    • 谢谢!在您回答后我发现了我的错误,我的连接字符串中有zeroDateTimeBehavior=convertToNull。我将其更改为zeroDateTimeBehavior=round。现在它工作正常! !
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 1970-01-01
    • 2011-06-27
    • 2017-07-17
    • 2020-12-12
    • 2019-03-26
    相关资源
    最近更新 更多