简体   繁体   中英

@SequenceGenerator's initValue and allocationSize are ignored and generator not assigned to @Id field (H2, HIbernate, Spring)

I use JPA in a Spring application configured to use embedded H2 database.

I have a User entity defined like this:

@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
}

Context is defined like this:

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

I can see from the log generated that MY_SEQ is generated. However, initialValue and allocationSize are completely ignored and the sequence is not assigned to the id field of USER

17:22:29.236 [main] DEBUG org.hibernate.SQL - create sequence 
17: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 (, 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]

What I am missing?

Your JPA set-up is correct but you have to keep in mind that the persistence provider will only take care of generating the id for you (additional query to the database for the next value of the sequence) when inserting through Hibernate or JPA API.

This will not happen when you perform the insertions 'by hand' in the data.sql file. You would have to invoke the sequence manually there:

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

Edit

This property: spring.jpa.hibernate.use-new-id-generator-mappings or hibernate.id.new_generator_mappings=true (if your not using spring boot) would allow for initialValue feature support.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM