【问题标题】:Cannot insert the value Null into column "ID" - Hibernate无法将值 Null 插入“ID”列 - 休眠
【发布时间】:2020-10-21 18:16:14
【问题描述】:

我创建了一个表及其 api,我正在通过邮递员进行验证。 这是我的表的主键:

 @Data
 @AllArgsConstructor
 @NoArgsConstructor
 @Entity
 @Table(name = "ALERT")
 public class Table Name{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ALERTID")
private Integer id; 

当我使用 Postman 验证这个 api 时,它给了我这个错误:

  SQL [n/a]; constraint [null]; nested exception is 
 org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL 
  into column 'ID', table 
  'CRM.dbo.ALERT'; 
  column does not allow nulls. INSERT fails.

我用同样的方式创建了许多其他表和它们的 api,它们工作正常。但只有这张桌子给了我这个错误。知道为什么我会收到此错误吗?

【问题讨论】:

  • 那么generalCoService.saveAlert(obj) 长什么样子?
  • 请查看我更新的问题@BenjaminMaurer

标签: java hibernate visual-studio-code


【解决方案1】:

@GeneratedValue(strategy = GenerationType.AUTO) 的行为取决于您的底层数据库。好像 MSSQL 不支持这个策略。

改用@GeneratedValue(strategy = GenerationType.IDENTITY)

JPA GenerationType.AUTO not considering column with auto increment

【讨论】:

  • 但是为什么这对除此之外的所有其他表都有效?
  • @Unknown 要回答这个问题,您应该显示您的“其他”表/实体。 id 属性上可能没有 @Id 注释,或者此列没有主键约束并且可以接受空值。或者别的什么
  • 还有数据库中的列类型是什么?
猜你喜欢
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
相关资源
最近更新 更多