java 尝试在休眠中指定属性的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10757260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:25:55  来源:igfitidea点击:

Trying to specify default value for property in hibernate

javahibernate

提问by opike

I'm getting the following error message from hibernate when attempting to insert a row into a table:

尝试在表中插入一行时,我从 hibernate 收到以下错误消息:

org.hibernate.exception.ConstraintViolationException: Column 'priority' cannot be null

org.hibernate.exception.ConstraintViolationException:列“优先级”不能为空

I know that I could put a line into the code to set the value but there are many other instances where the program relies on the default value in the database (db is mysql).

我知道我可以在代码中添加一行来设置值,但是还有许多其他情况下程序依赖于数据库中的默认值(db 是 mysql)。

I read somewhere that you can provide a default value in the hbm.xml file but hibernate is not recognizing it. Here's the corresponding section from JobQueue.hbm.xml

我在某处读到您可以在 hbm.xml 文件中提供默认值,但休眠无法识别它。这是 JobQueue.hbm.xml 中的相应部分

    <property name="priority" type="integer">
        <column name="priority" default="0" />
    </property> 

I suppose another option would be to modify the JobQueue.java file that gets generated (I'm using eclipse hibernate tools to auto generate the hibernate classes) but for now I'd like to try to get the hbm.xml configuration to work.

我想另一个选择是修改生成的 JobQueue.java 文件(我使用 eclipse 休眠工具来自动生成休眠类),但现在我想尝试让 hbm.xml 配置工作。

I'm using version 4.1.3 of the hibernate libraries and eclipse hibernate tools 3.4.0.x.

我正在使用 4.1.3 版的休眠库和 Eclipse 休眠工具 3.4.0.x。

采纳答案by opike

I ended up modifying the JobQueue.java POJO to set the default value. To make sure that the Code Generation of hibernate tools wouldn't overwrite this change, I set it up so that the code generation generates the files in a temp folder and then the necessary files are copied over to the permanent source location.

我最终修改了 JobQueue.java POJO 以设置默认值。为了确保休眠工具的代码生成不会覆盖此更改,我对其进行了设置,以便代码生成在临时文件夹中生成文件,然后将必要的文件复制到永久源位置。

回答by Firo

default="0"is only relevant for SchemaExport which generates the database schema. other than that hibernate completely ignores this setting. you could try to set not-null="true"for the column.

default="0"仅与生成数据库架构的 SchemaExport 相关。除了休眠完全忽略此设置。您可以尝试not-null="true"为列设置。

回答by Paulo Fidalgo

Unless you are not able to recreate the whole database schema, you can set the default value in the variable initialization. In your model set the priority to 0 in the initialization.

除非您无法重新创建整个数据库架构,否则您可以在变量初始化中设置默认值。在您的模型中,在初始化时将优先级设置为 0。

In your class:

在你的课堂上:

private Integer priority = 0;