In the last post, we managed to wire up a H2 database with our Spring Boot application. In this post, we will see how inserting records to table using Spring Boot looks like. As we do this, we will also add some functionality to our sample application.

To achieve our goal of inserting records, we will be using the repository interfaces provided by Spring Data JPA.

Spring Data JPA provides powerful abstractions that allows developers to get away from writing boilerplate code to setup tables. In order to create/read/update/delete records, all they have to do is wire up the entity with an appropriate interface.

We have already included the dependency in the pom.xml file. See below:

1
2
3
4
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Defining the Repository Interface

In the next step, we need to declare repository interface for our entity. Above all other features, this interface will act as a bridge between the Java class and the actual table in the database.

We want to keep all our repository interfaces in one place. So we will create new package called repositories under the base package. Inside this package we will create the interface and name it VehicleRepository.

1
2
3
4
5
6
7
8
9
package com.progressivecoder.demo.springbootstarter.repositories;

import com.progressivecoder.demo.springbootstarter.entities.Vehicle;
import org.springframework.data.repository.CrudRepository;

import java.util.UUID;

public interface VehicleRepository extends CrudRepository<Vehicle, UUID> {
}

Note what we are doing here.

We are extending the CrudRepository interface provided by Spring Data JPA. In other words, we are gettting CRUD operations for free. CRUD stands for Create, Read, Update, Delete.

Now that we’ve declared the interface, we can actually insert some records into our H2 database.

Command Line Runner

Spring Boot provides two interfaces that can be used to run specific pieces of code when an application starts up.

Command Line Runner is one such interface. Using this interface, we can write some logic that gets executed at the application start-up time. This approach is also used to bootstrap test data.

In the main class where we have the @SpringBootStarterApplication annotation, we can declare a class that implements CommandLineRunner interface. Then, we implement it’s run method and insert two vehicles in the Vehicle table.

See below code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@SpringBootApplication
public class SpringBootStarterApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootStarterApplication.class, args);
	}

}

@Component
class DemoCommandLineRunner implements CommandLineRunner{

	@Autowired
	private VehicleRepository vehicleRepository;

	@Override
	public void run(String... args) throws Exception {

		Vehicle audi = new Vehicle();
		audi.setId(UUID.randomUUID());
		audi.setVehicleIdentityNumber("Reg#1234");
		audi.setMake("Audi");
		audi.setModel("Q5");

		vehicleRepository.save(audi);

		Vehicle tesla = new Vehicle();
		tesla.setId(UUID.randomUUID());
		tesla.setVehicleIdentityNumber("Reg#6789");
		tesla.setMake("Tesla");
		tesla.setModel("Model S");

		vehicleRepository.save(tesla);
	}
}

Some important things to note:

  • We have placed @Component annotation on DemoCommandLineRunner class. This registers the class as a component. It also instructs Spring to create a bean for this class.
  • We have placed @Autowired annotation above the VehicleRepository. This tells Spring that an instance of the repository class needs to be injected as a dependency to DemoCommandLineRunner. There are various ways of dependency injection. However, using Autowired is the most explicit.
  • The VehicleRepository provides a save() method. The save() method is part of CrudRepository interface. It also expects an object of managed entity as an input parameter.

When the Spring context loads up, the CommandLineRunner should be executed. And the two records should be inserted into the table. However, to make sure, let’s check it out.

Run the application. Once it starts up successfully, visit the h2-console path. Then, once you connect to the database, you should be able to query the Vehicle table. As you can see in the below screenshot, the two vehicles we added are now stored in the database.

spring data jpa repository interface to insert records

The Next Step

Even though this approach works well for testing, it doesn’t go well with the needs of a real application.

In a real application, we would often be having some functionality where users should be able to create new records. Or update them. Or delete them. In other words, we need a way for users to interact with our database. In order to do so, we will expose our resources or model entities (in this case Vehicle) as REST resources.

We will start off on that in the next post. The code till this point is available on Github.


Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

3 Comments

E · June 29, 2019 at 4:48 am

Your posts on Spring Boot are great, but you keep forgetting to show the new imports you make on older files like this one… @Component and @Autowired will not resolve if you dont import new stuff.

    Saurabh Dashora · June 29, 2019 at 12:14 pm

    Hello, Thanks for the feedback. And yes, that’s a good point about imports if its helps making things more clear. I will update the code block soon.
    Of course, the code is available on Github for extra reference.

    someone · February 6, 2020 at 8:49 am

    i am testing

Leave a Reply

Your email address will not be published. Required fields are marked *