Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

Spring Data JDBC is a persistence framework that is not as complex as Spring Data JPA. It doesn't provide cache, lazy loading, write-behind, or many other features of JPA. Nevertheless, it has it's own ORM and provides most of the features we're used with Spring Data JPA like mapped entities, repositories, query annotations, and JdbcTemplate.

An important thing to keep in mind is that Spring Data JDBC doesn't offer schema generation. As a result, we are responsible for explicitly creating the schema.

2. Adding Spring Data JDBC to the Project

Spring Data JDBC is available to Spring Boot applications with the JDBC dependency starter. This dependency starter does not bring the database driver, though. That decision must be taken by the developer. Let's add the dependency starter for Spring Data JPA:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency> 

In this example, we're using the H2 database. As we mentioned early, Spring Data JDBC doesn't offer schema generation. In such a case, we can create a custom schema.sql file that will have the SQL DDL commands for creating the schema objects. Automatically, Spring Boot will pick this file and use it for creating database objects.

3. Adding Entities

As with the other Spring Data projects, we use annotations to map POJOs with database tables. In Spring Data JDBC, the entity is required to have an @Id. Spring Data JDBC uses the @Id annotation to identify entities.

Similar to Spring Data JPA, Spring Data JDBC uses, by default, a naming strategy that maps Java entities to relational database tables, and attributes to column names. By default, the Camel Case names of entities and attributes are mapped to snake case names of tables and columns, respectively. For example, a Java entity named AddressBook is mapped to a database table named address_book.

Also, we can map entities and attributes with tables and columns explicitly by using the @Table and @Column annotations. For example, below we have defined the entity that we're going to use in this example:

public class Person {
    @Id
    private long id;
    private String firstName;
    private String lastName;
    // constructors, getters, setters
}

We don't need to use the annotation @Table or @Column in the Person class. The default naming strategy of Spring Data JDBC does all the mappings implicitly between the entity and the table.

4. Declaring JDBC Repositories

Spring Data JDBC uses a syntax that is similar to Spring Data JPA. We can create a Spring Data JDBC repository by extending the Repository, CrudRepository, or PagingAndSortingRepository interface. By implementing CrudRepository, we receive the implementation of the most commonly used methods like save, delete, and findById, among others.

Let's create a JDBC repository that we're going to use in our example:

@Repository 
public interface PersonRepository extends CrudRepository<Person, Long> {
}

If we need to have pagination and sorting features, the best choice would be to extend the PagingAndSortingRepository interface.

5. Customizing JDBC Repositories

Despite CrudRepository built-in methods, we need to create our methods for specific cases. One important thing to note is that Spring Data JDBC does not support derived queries. This means that we can't just write the method name and expect that Spring Data JDBC generates the query.

Every time we write a custom method, we need to decorate it with the @Query annotation. Inside the @Query annotation, we add our SQL command. In Spring Data JDBC, we write queries in plain SQL. We don't use any higher-level query language like JPQL. As a result, the application becomes tightly coupled with the database vendor.

For this reason, it also becomes more difficult to change to a different database.

Another important difference is that Spring Data JDBC does not support the referencing of parameters with index numbers. In this version of Spring Data JDBC, we're able only to reference parameters by name.

With the @Modifying annotation, we can annotate query methods that modify the entity.

Now let's customize our PersonRepository with a non-modifying query and a modifying query:

@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {

    @Query("select * from person where first_name=:firstName")
    List<Person> findByFirstName(@Param("firstName") String firstName);

    @Modifying
    @Query("UPDATE person SET first_name = :name WHERE id = :id")
    boolean updateByFirstName(@Param("id") Long id, @Param("name") String name);
}

6. Populating the Database

Finally, we need to populate the database with data that will serve for testing the Spring Data JDBC repository we created above. So, we're going to create a database seeder that will insert dummy data. Let's add the implementation of database seeder for this example:

@Component
public class DatabaseSeeder {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void insertData() {
        jdbcTemplate.execute("INSERT INTO Person(first_name,last_name) VALUES('Victor', 'Hugo')");
        jdbcTemplate.execute("INSERT INTO Person(first_name,last_name) VALUES('Dante', 'Alighieri')");
        jdbcTemplate.execute("INSERT INTO Person(first_name,last_name) VALUES('Stefan', 'Zweig')");
        jdbcTemplate.execute("INSERT INTO Person(first_name,last_name) VALUES('Oscar', 'Wilde')");
    }
}

As seen above, we're using Spring JDBC for executing the INSERT statements. In particular, Spring JDBC handles the connection with the database and lets us execute SQL commands using JdbcTemplates. This solution is very flexible because we have complete control over the executed queries.

7. Conclusion

To summarize, Spring Data JDBC offers a solution that is as simple as using Spring JDBC — there is no magic behind it. Nonetheless, it also offers a majority of features that we're accustomed to using Spring Data JPA.

One of the biggest advantages of Spring Data JDBC is the improved performance when accessing the database as compared to Spring Data JPA. This is due to Spring Data JDBC communicating directly to the database. Spring Data JDBC doesn't contain most of the Spring Data magic when querying the database.

One of the biggest disadvantages when using Spring Data JDBC is the dependency on the database vendor. If we decide to change the database from MySQL to Oracle, we might have to deal with problems that arise from databases having different dialects.

The implementation of this Spring Data JDBC tutorial can be found over on GitHub.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Emmanouil Tzagkarakis
Emmanouil Tzagkarakis
1 month ago

It also does not support composite keys yet, which is a deal breaker sometimes

Loredana Crusoveanu
1 month ago

Hi Emmanouil,
Yeah, that’s true, though the support may be added in the future: https://jira.spring.io/browse/DATAJDBC-352

KPNC
KPNC
1 month ago

Spring Data JDBC does not support derived queries

In fact version 2 does support that feature

Loredana Crusoveanu
1 month ago
Reply to  KPNC

Hi Chris,
That’s correct, we’ll update the article to reflect the upgrade.
Thanks!

Mrudul
Mrudul
26 days ago

One of the biggest advantages that you can get from using Spring Data JDBC is that it will force you to follow the rules of DDD design like using aggregates. A great explanation why this design can help you can be found https://dddcommunity.org/library/vernon_2011/.

Comments are closed on this article!