gpt4 book ai didi

java - @SequenceGenerator 的 initValue 和 AllocationSize 被忽略,生成器未分配给 @Id 字段(H2、HIbernate、Spring)

转载 作者:行者123 更新时间:2023-11-30 02:33:03 48 4
gpt4 key购买 nike

我在配置为使用嵌入式 H2 数据库的 Spring 应用程序中使用 JPA。

我有一个如下定义的用户实体:

@Entity
@SequenceGenerator(name = "myseq", sequenceName = "MY_SEQ", initialValue = 1000, allocationSize = 1)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "myseq")
private Long id;

@Column(name = "USERNAME")
private String userName;

@Column(name = "PASSWORD_ENCODED")
private String passwordEncoded;

@ManyToMany
@JoinTable(name = "USER_ROLES", joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID"))
private Set<Role> roles;
}

//getters
}

上下文定义如下:

@Configuration
@EnableWebMvc
@EnableWebSecurity
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = "my.package")
@EntityScan(basePackages = "my.package")
@ComponentScan(basePackages = "my.package" )
public class AuthenticationWebAppContext extends WebSecurityConfigurerAdapter {
}

从生成的日志中可以看到生成了 MY_SEQ。但是,initialValue和allocationSize被完全忽略,并且序列没有分配给USER的id字段

17:22:29.236 [main] DEBUG org.hibernate.SQL - create sequence my_seq start with 1 increment by 117:22:29.237 [main] DEBUG org.hibernate.SQL - create table role (id bigint generated by default as identity, name varchar(255), primary key (id))17:22:29.248 [main] DEBUG org.hibernate.SQL - create table user (id bigint not null, password_encoded varchar(255), username varchar(255), primary key (id))

So, when a row insert is attempted by data.sql file, I got the following error:

Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ID"; SQL statement:
INSERT INTO user (USERNAME, PASSWORD_ENCODED) VALUES ('user1', '<some_giberish>') [23502-194]

我缺少什么?

最佳答案

您的 JPA 设置是正确的,但您必须记住,持久性提供程序只会在通过 Hibernate 插入时为您生成 id(对数据库进行额外查询以获取序列的下一个值) JPA API。

当您在 data.sql 文件中“手动”执行插入时,不会发生这种情况。您必须在那里手动调用序列:

INSERT INTO user (ID, USERNAME, PASSWORD_ENCODED)
VALUES (NEXTVAL('my_seq')'user1', '<some_giberish>')

编辑

此属性:spring.jpa.hibernate.use-new-id-generator-mappingshibernate.id.new_generator_mappings=true (如果您不使用 spring boot )将允许 initialValue 功能支持。

关于java - @SequenceGenerator 的 initValue 和 AllocationSize 被忽略,生成器未分配给 @Id 字段(H2、HIbernate、Spring),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43785716/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com