HomeSpring BootSpring Data JDBC Examples

Spring Data JDBC Examples

In this quick tutorial we will walkthrough a Spring Data JDBC Example with Spring Boot to demonstrate Object Mappings and configurations, and testing JDBC repositories, CRUD operations using Rest Controllers and Unit tests.

At the end of this tutorial you will find more Spring Data JDBC examples that we have provided.

1. Maven Dependency Configurations

1.1. Used Technologies :

  1. Spring Boot 2.3.0.RELEASE
  2. Spring Data JDBC 2.0.0.RELEASE
  3. Spring Framework 5.2.6.RELEASE
  4. H2 / MySql DB
  5. Lombok 1.18.12
  6. JUnit 5

1.2. Maven Dependencies

To start working with Spring Boot with Spring Data JDBC you need dependency spring-boot-starter-data-jdbc. Use Lombok to avoid boiler plate code. Here is complete dependency list used in the example application.


2. Spring Boot Configuration Properties

Here is complete configuration properties in

## webserver port mapping, default is 8080
## custom root context, default is application name

## H2 DB properties

## Mysql DB properties
#spring.datasource.password=password = org.hibernate.dialect.MySQL5InnoDBDialect

## Enables H2 console (A simple web interface to access H2 DB)

## custom H2 console url, Default path is 'h2-console'

## to Json Pretty print in browser

3. Model Mapping

When you are working with Spring Data JDBC, you’ll need to create entities that mapped to the Data Base table. To create Entities the class should follow the aggregate design of Domain Driven Design (DDD) and Entity Naming Strategy.

Following is simple mapping between User Table and User Entity.

3.1. User Table Structure :

		`USER_NAME` varchar(45) NOT NULL,
		`PASSWORD` varchar(45) NOT NULL,
		`USER_TYPE` varchar(45) NOT NULL,
		`DOB` date NOT NULL,

3.2. Entity Mapping for User Table :

  1. Lombok @Data is used to avoid generating boiler plate code (setters/getters, toString, hashcode, equals methods and RequiredArgsConstructor).
  2. Entity class name and DB table name should be same, otherwise map table name with @Table at class level like @Table("USER_TABLE") if table name “USER_TABLE”.
  3. To map DB Table identifier to the entity field, it must be annotated with @Id.
  4. Table Column name and field name must be same for auto mapping otherwise use @Column annotation to map fields to the DB Table column.
  5. To ignore fields to not persist in DB use Spring @Transient annotation.
@Data // lomok
public class User {

	private Long id;
	private String userName;
	private String password;
	private Date createdTime;
	private Date updatedTime;
	@Column("DOB") // to map db column if property not same as column name
	private Date dateofBirth;
	private UserType userType; // Enum Type // to not persist into DB (just to expose to view/client)
	private String dateOfBirthString;
	// to display on view
	public String getDateOfBirthString() {
		return this.dateofBirth.toString();
public enum UserType {

4. Create a JDBC Repository

Spring Data JDBC 2.x.x supports CrudRepository, PagingAndSortingRepository to make it possible to work with most common DB operations. In this tutorial we have used CrudRepository.

public interface UserRepository extends CrudRepository<User, Long>{


5. Test the configurations and Mapping

Implemented a Rest Controller and JUnit 5 tests to access User table data from DB. First Let’s have look in to unit tests.

5.1. JUnit5 Test Case to test CRUD operations :

@TestMethodOrder(value = OrderAnnotation.class) // to run tests in order
public class Basic_Mapping_Test extends BaseTest {

	private UserRepository userRepository;
	@DisplayName("Create-User-Test ")
	void createUserTest() {
		User created =;
		assertTrue(created != null && created.getId() != null);
	@DisplayName("Update-User-Test ")
	void updateUserTest() {
		// Read all users
		List<User> allUsers = (List<User>) userRepository.findAll();
		allUsers.forEach(user -> {
			User updated =;
		// userRepository.saveAll(allUsers); // batch update
	@DisplayName("Delete-User-Test ")
	void deleteUserTest() {
		// Read all users
		List<User> allUsers = (List<User>) userRepository.findAll();
		allUsers.forEach(user -> {
		// userRepository.deleteAll(allUsers); //batch delete

5.2. Rest Controller to access User Data :

A Spring REST controller to access CRUD operations using Spring Data JDBC CrudRepository.

public class UserController {

	private UserRepository userRepository;

	public UserController() {

	// Read - get all

	public List<User> getAllUsers() {
		return (List<User>) userRepository.findAll();

	// Read - find one

	public ResponseEntity<User> getUserById(@PathVariable(value = "id") final Long userId) {

		User user = userRepository.findById(userId)
				.orElseThrow(() -> new NoSuchElementException("User not availbele for Id :" + userId));

		return ResponseEntity.ok().body(user);

	// Write - create

	public void createUser(@Valid @RequestBody User user) {

		System.out.println(user); // Just to inspect values for demo;

	// Write - update

	public void updateUser(@PathVariable("id") final long id, @RequestBody final User user) {
		User findUser = userRepository.findById(id)
				.orElseThrow(() -> new NoSuchElementException("User not availbele for Id :" + id));;

	// Write - delete

	public void deleteUser(@PathVariable final long id) {
		User user = userRepository.findById(id)
				.orElseThrow(() -> new NoSuchElementException("User not availbele for Id :" + id));

6. Conclusion

In this tutorial we walked through a Spring Data JDBC with Spring Boot example application to demonstrate object mapping, configurations. Also covered testing Spring Data JDBC CrudRepository operations and access them via a REST Controller.

Checkout source code at Git Hub.

Other Spring Data JDBC Tutorials :

  1. Spring Data JDBC – Embedded Entities
  2. Spring Data JDBC – Pagination
  3. Spring Data JDBC – One-to-Many
  4. Spring Data JDBC – Many-to-Many
  5. Spring Data JDBC – One-to-One
  6. Spring Data JDBC – Query Derivation
  7. Spring Boot – Loading Initial data

7. References

  1. Spring Documentation
  2. Lombok Data
  3. Lombok @RequiredArgsConstructor
  4. JUnit 5 Tutorial
  5. Junit 5 Test Order
  6. Spring Boot Junit 5 Test


Please enter your comment!
Please enter your name here