Miraj Hamid
Miraj Hamid

Reputation: 662

Is there a way to override JPA saveAll method to used customized UPSERT query?

I am trying to override the JpaRepository saveAll method to use the custom UPSERT query in java SpringBoot. Is it possible?

Upvotes: 0

Views: 2508

Answers (2)

Miraj Hamid
Miraj Hamid

Reputation: 662

I used JdbcTemplate (NamedParameterJdbcTemplate)

//Bean
@Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
    JdbcTemplate template = new JdbcTemplate(hikariDataSource);
    template.setQueryTimeout(Integer.parseInt(queryTimeout));
    return new NamedParameterJdbcTemplate(template);
}

Then

//Autowire NamedParameterJdbcTemplate

MapSqlParameterSource[] paramsArray = 
mapperClass.mapDTOstoSqlParameterSource(items);
namedParameterJdbcTemplate.batchUpdate(SQL_qUERY, paramsArray);

Then

//Mapper class
public static MapSqlParameterSource[] 
mapDTOstoSqlParameterSource(List<ItemDTO> items) {

    List<MapSqlParameterSource> params = new ArrayList<>();
    for (ItemDTO obj : items) {
        MapSqlParameterSource source = new MapSqlParameterSource();
        source.addValue("queryPara1", obj.getID());
        source.addValue("queryPara2", obj.getSomething());
        
        params.add(source);
    }

    return params.toArray(MapSqlParameterSource[]::new);
}

Upvotes: 0

Simon Martinelli
Simon Martinelli

Reputation: 36203

As it's only one repository you can create a custom repository like this. I assume that the Entity name is User:

Your interface with only this saveAll Method

interface CustomizedUserRepository {
    void savAllWithUpsert(Iterator<User> entities);
}

Then you have to implement the interface

class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  public void savAllWithUpsert(Iterator<User> entities) {
    // Your custom implementation
  }
}

The most important part of the class name that corresponds to the fragment interface is the Impl postfix.

And finally use but all together:

interface UserRepository extends JpaRepository<User, Long>, CustomizedUserRepository {
}

Please also read the full docuementaion: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.single-repository-behavior

Upvotes: 2

Related Questions