Java 休眠/SQLException:字段没有默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21244110/
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
Hibernate / SQLException: field doesn't have default value
提问by Samuel Smith
mySQL Table generated using:
使用以下方法生成的 mySQL 表:
CREATE TABLE `actors` (
`actorID` INT(11) NOT NULL,
`actorName` VARCHAR(255) NOT NULL,
PRIMARY KEY AUTO_INCREMENT (actorID)
);
Mapped class:
映射类:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "actorID", length = 11, unique = true, nullable = false)
private int actorID;
....
Error:
错误:
ERROR: Field 'actorID' doesn't have a default value
This error is hit when trying to create a new Actor object, and saving it to the database.
尝试创建新的 Actor 对象并将其保存到数据库时会发生此错误。
I've tried using other generation strategies, and dropping/rebuilding tables / entire database, as per the answers to similar questions. No luck so far.
根据类似问题的答案,我尝试使用其他生成策略,并删除/重建表/整个数据库。到目前为止没有运气。
Thank you for your time, Samuel Smith
谢谢你的时间,塞缪尔史密斯
EDIT: Dropping the table and recreating it using the SQL syntax shown by shippi seemed to solve the problem for me.
编辑:删除表并使用shippi 显示的SQL 语法重新创建它似乎解决了我的问题。
采纳答案by shippi
Just try to use
尝试使用
@GeneratedValue(strategy=GenerationType.AUTO)
@Id
@Column(name = "actorID")
private int actorID;
This should fix your issue. Leave the actorID null if saving.
这应该可以解决您的问题。如果保存,则将 actorID 留空。
Ensure also that the DB works fine, try to write an insert statement without inserting the ID and lets see whether the pure insert is working. If the direct insert is working to the database you could start to troubleshoot hibernate.
还要确保数据库工作正常,尝试在不插入 ID 的情况下编写插入语句,然后让我们看看纯插入是否正常工作。如果直接插入对数据库起作用,您可以开始对休眠进行故障排除。
And a small point, I use to define the PH and Auto increment in the same line where defining the column:
还有一点,我用来在定义列的同一行中定义 PH 和自动增量:
actorID
INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
actorID
INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
but it should work either way.
但它应该以任何一种方式工作。
回答by alvaro torrico
Your error is in your table definition.
您的错误在您的表定义中。
Must be:
必须是:
CREATE TABLE `actors` (
`actorID` INT(11) NOT NULL AUTO_INCREMENT,
`actorName` VARCHAR(255) NOT NULL,
PRIMARY KEY AUTO_INCREMENT (actorID)
);
You missed AUTO_INCREMENT in actorID.
您错过了 actorID 中的 AUTO_INCREMENT。