Spring JdbcAggregateTemplate Example

Spring’s JdbcAggregateTemplate gives you more granular control over the operations that are being performed on your database. JdbcAggregateTemplate exposes operations that are used by Spring Repositories internally, allowing you to invoke database operations that would not otherwise be available using a standard JDBC Repository.

This template can be useful for situations when you want to bypass a Spring Repository’s save method and directly insert a record into the database. For example, say you want to insert a record that has a custom ID into a table. If you were to use a conventional Spring Repository, Spring JDBC would incorrectly attempt to update a non-existant record instead of inserting a new one.

By using the JdbcAggregateTemplate, we can override this typical behavior in Spring JDBC and manually insert the record instead of calling update which could result in your application throwing an IncorrectUpdateSemanticsDataAccessException.

import org.springframework.dao.IncorrectUpdateSemanticsDataAccessException;
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;

class DirectInsertExample { 

    @Autowired
    JdbcAggregateTemplate template;
    
    @Autowired
    WidgetRepository widgets; // Our custom 'widget' repository
    
    public void insertCustomId() throws Exception {
    
        // Create a new object to insert into the DB
        Widget widget = new Widget();
        widget.id = 123;
        widget.name = "example";
        
        // Insert an object with a custom ID in the database using Spring JDBC
        template.insert(widget);
        
        // Note: if we had attempted to use a JdbcTemplate to save the object Spring would have returned an error.
        //widgets.save(widget);
        
        // Check to see if it worked by retrieving our object from the database!
        Widget widgetDb = widgets.findById(123).get();
    }
}