H2数据库:NULL不允许用于列“ID”当使用jdbcTemplate插入记录时 [英] H2 database: NULL not allowed for column "ID" when inserting record using jdbcTemplate
本文介绍了H2数据库:NULL不允许用于列“ID”当使用jdbcTemplate插入记录时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用hibernate的hbm2ddl自动生成模式。这是我的域名:
@Entity
public class Reader {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
@Column(nullable = false,unique = true)
字符串名称;
@Enumerated(EnumType.STRING)
性别性别;
int age;
Date registeredDate = new Date();
// getter and setter ...
}
当我使用hibernate保存 reader
时,它可以正常工作,因为它会为 reader 生成一个id。但是,当我使用jdbcTemplate插入带有纯SQL的记录时,它会报告错误:
org.springframework.dao.DataIntegrityViolationException: StatementCallback;
SQL [插入读者(姓名,性别,年龄)值('Lily','FEMALE',21)];
NULL不允许列ID;
SQL语句:插入读者(姓名,性别,年龄)值('Lily','FEMALE',21)[23502-192];
嵌套的异常是org.h2.jdbc.JdbcSQLException:NULL不允许列ID;
SQL语句:insert into reader(name,gender,age)values('Lily','FEMALE',21)[23502-192]
如何解决这个问题?
- 我调试发现生成的hb2ddl的DDL是
create table Book(id bigint not null,author varchar(255),name varchar(255),price double not null,type varchar(255),primary key(id))
。这似乎是hiberate以自己的方式处理id战略,但如何?
-
@GeneratedValue(strategy = GenerationType.AUTO)
应该在DDL语句中生成自动增量
,但我没有找到。 .IDENTITY 代替 - I debug to find that the DDL of hb2ddl generated is
create table Book (id bigint not null, author varchar(255), name varchar(255), price double not null, type varchar(255), primary key (id))
. It seems that the hiberate handle the id stratege in its own way but how? - The
@GeneratedValue(strategy=GenerationType.AUTO)
should generateauto increment
in the statement of the DDL but I didn't find that. Did I miss it?
strategy = GenerationType.AUTO
也可能是错误的hibernate .dialect
试一下
hibernate.dialect = org.hibernate.dialect.H2Dialect
I use hibernate's hbm2ddl to generate schema automatically. Here is my domain:
@Entity
public class Reader {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Long id;
@Column(nullable=false,unique=true)
String name;
@Enumerated(EnumType.STRING)
Gender gender;
int age;
Date registeredDate = new Date();
// getter and setter ...
}
When I using hibernate to save a reader
, it works fine as expected as it generats a id to the reader
. However when I use jdbcTemplate to insert a record with pure SQL, it report an error:
org.springframework.dao.DataIntegrityViolationException: StatementCallback;
SQL [insert into reader(name,gender,age) values('Lily','FEMALE',21)];
NULL not allowed for column "ID";
SQL statement:insert into reader(name,gender,age) values('Lily','FEMALE',21) [23502-192];
nested exception is org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ID";
SQL statement: insert into reader(name,gender,age) values('Lily','FEMALE',21) [23502-192]
How to solve this?
解决方案
Try to use strategy=GenerationType.IDENTITY
instead of the strategy=GenerationType.AUTO
Also could be wrong hibernate.dialect Try the
hibernate.dialect=org.hibernate.dialect.H2Dialect
这篇关于H2数据库:NULL不允许用于列“ID”当使用jdbcTemplate插入记录时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文