我使用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 ... }
当我使用hibernate保存a时reader,它会为ID生成ID,因此可以按预期工作reader。但是,当我使用jdbcTemplate通过纯SQL插入记录时,它报告一个错误:
reader
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]
如何解决呢?
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
尝试使用strategy=GenerationType.IDENTITY而不是strategy=GenerationType.AUTO
strategy=GenerationType.IDENTITY
strategy=GenerationType.AUTO
hibernate.dialect也可能是错误的
hibernate.dialect=org.hibernate.dialect.H2Dialect