我使用hibernate的hbm2ddl自动生成模式.这是我的域名:
@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 ...
}
Run Code Online (Sandbox Code Playgroud)
当我使用hibernate来保存a时reader,它可以正常工作,因为它会产生一个id reader.但是,当我使用jdbcTemplate插入带有纯SQL的记录时,它会报告错误:
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]
Run Code Online (Sandbox Code Playgroud)
怎么解决这个?
create table Book (id bigint not null, author varchar(255), name varchar(255), price double not null, type varchar(255), primary key (id)).似乎嫌疑人以自己的方式处理了这个问题,但是如何处理?@GeneratedValue(strategy=GenerationType.AUTO)应产生auto increment的DDL的语句,但我没有发现.我错过了吗?Sta*_*avL 22
尝试使用strategy=GenerationType.IDENTITY而不是strategy=GenerationType.AUTO
也可能是错误的hibernate.dialect试试
hibernate.dialect=org.hibernate.dialect.H2Dialect
Run Code Online (Sandbox Code Playgroud)
小智 22
如果您使用 H2 依赖项版本:“ 2.0.202 ”或更高版本,那么其他 2 种方法可能会起作用。
1:使用H2版本:“ 1.4.200 ”('com.h2database:h2:1.4.200')
2:将“ ;MODE=LEGACY ”附加到 JDBC url ( test case -> jdbc:h2:mem:test;MODE=LEGACY)
如果DB支持一个序列,Hibernate 5.2.x(Spring Boot 2.x)会更改序列的默认策略。因此,根据此顺序,必须创建with strategy=GenerationType.AUTO,hibernate_sequence但id不会自动递增,如下所示:
create table users (id integer not null, ...)
Run Code Online (Sandbox Code Playgroud)
代替
create table table_name(id int default hibernate_sequence.nextval primary key, ...);
Run Code Online (Sandbox Code Playgroud)
(请参阅HHH-13268)。有几种解决方案:
@GeneratedValue为strategy = GenerationType.IDENTITYspring.jpa.properties.hibernate.id.new_generator_mappings=false(spring-boot别名spring.jpa.hibernate.use-new-id-generator-mappings)INSERT INTO TABLE(ID, ...) VALUES (hibernate_sequence.nextval, ...)这个问题已在 Hibernate 5.6.5 (Spring Boot 2.6.4) 中得到解决,因此 H2 版本 2.0.202(或更高版本)可以再次工作。
请参阅https://github.com/hibernate/hibernate-orm/pull/4524以供参考。
| 归档时间: |
|
| 查看次数: |
15045 次 |
| 最近记录: |