You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

H2数据库IDENTITY列插入数据失败的技术求助

Fixing the "NULL not allowed for column USER_ID" Error in H2 Database

Hey Anand, let's break down why you're hitting this error and how to fix it quickly.

First, let's look at your table creation statement—there's a tiny syntax issue that's throwing H2 off: you have an extra comma at the end of your column definitions. That might seem trivial, but it can cause H2 to misinterpret the IDENTITY column's auto-increment behavior, treating it like a regular non-null column instead of one that generates values automatically.

Step 1: Correct Your DDL Statement

Here's the fixed version of your table creation SQL, with the extra comma removed:

CREATE TABLE IF NOT EXISTS USER (
    USER_ID IDENTITY,
    USER_NAME VARCHAR(30) NOT NULL,
    USER_PASSWORD VARCHAR(256) NOT NULL
);

Step 2: Verify Auto-Increment Behavior (If Needed)

H2's IDENTITY type is actually an alias for BIGINT AUTO_INCREMENT, so it should auto-generate values by default. But if you still run into issues after fixing the comma, you can explicitly define the column with AUTO_INCREMENT and set it as the primary key for clarity:

CREATE TABLE IF NOT EXISTS USER (
    USER_ID BIGINT AUTO_INCREMENT PRIMARY KEY,
    USER_NAME VARCHAR(30) NOT NULL,
    USER_PASSWORD VARCHAR(256) NOT NULL
);

Step 3: Run Your Insert Statement Again

Once your table is created correctly, your original insert query will work perfectly—you don't need to provide a value for USER_ID because H2 will handle generating it for you:

INSERT INTO USER (USER_NAME, USER_PASSWORD) VALUES ('Anand', 'Anand$');

Why Did This Happen?

That extra comma in your DDL confused H2's parser, preventing it from recognizing USER_ID as an auto-incrementing column. Without that auto-increment flag, H2 expects you to provide a value for the non-null column, hence the "NULL not allowed" error.

内容的提问来源于stack exchange,提问作者Anandhakrishnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:12:27