Bulk insert: JdbcTemplate vs JPA

30 Views Asked by At

The question want to be really pointed.

I am not interested in knowing in general strengths and weaknesses of the two solutions.

I just need to analyze the performance of the two solutions in the context of bulk insert.

That is, with a table like this:

create table myEntity
(
    id   bigserial not null,
    name varchar(255) unique,
    primary key (id)
);

and this Entity definition:

@Data
@Entity
public class TestEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String name;
}

if the JPA solution is:

// spring.jpa.properties.hibernate.jdbc.batch_size = 1000 // set by configuration
myEntityRepo.saveAll(Iterable<S> entities)

and the JDBC (JdbcTemplate) solution is:

jdbcTemplate.batchUpdate("""
                        INSERT INTO myEntity(name)
                        VALUES (?)""",
                entities,
                1000,
                (ps, e) -> {
                    ps.setString(1, e.getName());
                });

is it normale to have a 15x performance difference between the two approach?

With a local PostgreSQL I'm able to insert 1.000.000 of entities in about 3 seconds using JdbcTemplate, while it takes 45 seconds with JPA.

I'm making something wrong or these are the normal differences that I have to accept?

0

There are 0 best solutions below