Batch save for Postgresql sequence does't work very well using hibernate

Viewed 32

I want to Batch save data to Postgresql

see demo in github https://github.com/coding2world/sb-jpa-batch-insert-demo

first, I write java code like this. below is pojo’s definition.

@Data
@Entity
@Table(name = "city")
@AllArgsConstructor
public class City {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "city_id_gen")
    @SequenceGenerator(name = "city_id_gen", sequenceName = "public.city_id_seq",
            allocationSize = 5)
    private Long id;
    private String name;
    private int population;

    public City(String name, int population) {
        this.name = name;
        this.population = population; 
    }
    public City() { }
}

Repository class.

public interface CityRepo extends JpaRepository<City, Long> {}

invoke the Repository class.

cityRepo.saveAll(range(1, 10)
                .mapToObj(i -> new City("beautiful", (int)System.currentTimeMillis()/1000))
                .collect(toList()));

second is my sql.

CREATE TABLE
    city(id serial PRIMARY KEY, name VARCHAR(255), population integer);

My question below:

When I call SELECT nextval('city_id_seq') return 100. It means 99 and 98 have been used.

Suppose the value of the parameter named allocationSize of the annotation named SequenceGenerator is 3 , So hibernate should generate 3 sequences once call SELECT nextval('city_id_seq'). According to the below code

org.hibernate.id.enhanced.PooledOptimizer#generate

SELECT nextval('city_id_seq') return 100 , the 3 sequences are 98, 99, 100. But 99 and 98 have been used.

I think Hibernate should call

SELECT setval ('city_id_seq', nextval ('city_id_seq')+3)

is returns 102. the 3 sequence is 100, 101, 102.

I’m not sure if Hibernate has some function to satisfy my demand.

1 Answers
Related