TraitsWu 2015-10-08 08:15 采纳率: 0%
浏览 1504

Hibernate 自动生成日期值

 <class name="com.traitswu.zone.entity.User" table="user">
        <id name="id" type="int" column="id">
            <generator class="native"/>
        </id>
        <property name="createDate" generated="insert" not-null="true" type="java.util.Date">
            <column name="createDate" sql-type="timestamp" default="CURRENT_TIMESTAMP"/>
        </property>
        <property name="modifiedDate" generated="always" not-null="true" type="java.util.Date">
            <column name="modifiedDate" sql-type="timestamp" default="CURRENT_TIMESTAMP"/>
        </property>
        <property name="userName" type="string" not-null="true" length="50" unique-key="account_unique"/>
        <property name="passWord" type="string" not-null="true" length="50" unique-key="account_unique"/>
    </class>

为什么没有自动生成日期值(exception: Caused by: java.sql.SQLException: Field 'createDate' doesn't have a default value)

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-04 10:45
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    在Hibernate中,generated="always" 用于指定字段的生成方式为always,即当插入时自动设置。然而,not-null="true"type="java.util.Date" 的组合会导致createdDate字段无法默认填充。

    为了使createdDate字段能够自动填充,您需要将not-null="true"改为nullable="false"。这样可以确保createdDate字段不能被设置为null,并且其值将被自动填充。

    修改后的代码如下:

    <class name="com.traitswu.zone.entity.User" table="user">
            <id name="id" type="int" column="id">
                <generator class="native"/>
            </id>
            <property name="createDate" generated="always" nullable="false" type="java.util.Date">
                <column name="createDate" sql-type="timestamp" default="CURRENT_TIMESTAMP"/>
            </property>
            ...
    </class>
    

    这样,即使在创建用户对象时未提供createDate字段的值,系统也会根据当前时间自动为其分配一个值。

    评论

报告相同问题?