Clik here to view.

1. Overview
IBM Db2 is a cloud-native, relational database system that also supports semi-structured data such as JSON and XML. It’s designed to handle large volumes of data at low latency.
In this tutorial, we’ll set up the Community Edition of a Db2 database server inside a Docker container using a docker-compose.yml file. Then, we’ll connect to it using its JDBC driver in a Spring Boot application.
2. Db2 Database
The Db2 database is known for efficiently handling large volumes of data with high throughput. It can handle structured and semi-structured data, making it versatile for different data models. It’s suitable for both microservice and monolithic applications.
Also, the database system requires a subscription to access its full capabilities. However, a free Community Edition is available, but it’s limited to a maximum storage of 16 GiB and four CPU cores. This version could be ideal for testing purposes or small-scale applications with limited resource needs.
3. Setup
To begin, let’s set up dependencies for a Spring Boot application and configure a Db2 database server inside a Docker container.
3.1. Maven Dependencies
Let’s bootstrap a Spring Boot application by adding the spring-boot-starter-web and spring-boot-starter-data-jpa dependencies to the pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>3.4.3</version>
</dependency>
The spring-boot-starter-web dependency allows us to create a web application, including RESTful APIs and MVC applications.
spring-boot-starter-data-jpa provides an Object Relational Mapping (ORM) tool, simplifying database interaction by abstracting native queries, except when explicitly defined.
Also, let’s add the com.ibm.db2 dependency to the pom.xml:
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>jcc</artifactId>
<version>12.1.0.0</version>
</dependency>
The com.ibm.db2 dependency provides the Db2 JDBC driver, enabling us to establish a connection to the Db2 database server.
3.2. Db2 Docker Compose File
Furthermore, let’s define a docker-compose.yml file in our project root directory to run the database server within a Docker container:
services:
db2:
image: icr.io/db2_community/db2
container_name: db2server
hostname: db2server
privileged: true
restart: unless-stopped
ports:
- "50000:50000"
environment:
LICENSE: accept
DB2INST1_PASSWORD: mypassword
DBNAME: testdb
BLU: "false"
ENABLE_ORACLE_COMPATIBILITY: "false"
UPDATEAVAIL: "NO"
TO_CREATE_SAMPLEDB: "false"
volumes:
- db2_data:/database
healthcheck:
test: ["CMD", "su", "-", "db2inst1", "-c", "db2 connect to testdb || exit 1"]
interval: 30s
retries: 5
start_period: 60s
timeout: 10s
volumes:
db2_data:
driver: local
The configuration above pulls the latest Db2 community image. Also, it creates a user, sets a password, and initializes a database. In this case, the username is db2inst1, the password is mypassword, and the database name is testdb.
Next, let’s run the docker compose up command to start the database server.
4. Defining Connection Credentials in application.properties
Now that our database server is up, let’s define the connection details in the application.properties file:
spring.datasource.url=jdbc:db2://localhost:50000/testdb
spring.datasource.username=db2inst1
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.ibm.db2.jcc.DB2Driver
spring.jpa.database-platform=org.hibernate.dialect.DB2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Here, we define the database URL which includes the host, the port, and the name of the database we’re connecting to. Additionally, the URL begins with jdbc:db2, which is a JDBC subprotocol indicating that the connection is to a Db2 database.
Next, we specify the username and password as configured in the docker-compose.yml file.
Importantly, setting the spring.datasource.driver-class-name property ensures Spring Boot loads the correct Db2 JDBC driver.
5. Testing the Connection
Next, let’s confirm the connection to the database by persisting a record to testdb.
5.1. Entity Class
First, let’s create an entity class named Article:
@Entity
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String body;
private String author;
// standard constructor, getters and setters
}
The entity class is mapped to the database table and its column.
Next, let’s define a repository to handle database operations:
public interface ArticleRepository extends JpaRepository<Article, Long> {
}
Now, we can persist an entity into the database by injecting the repository into our controller.
5.2. Controller Class
Furthermore, let’s create a controller class:
@RestController
public class ArticleController {
private final ArticleRepository articleRepository ;
public ArticleController(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}
}
In the code above, we use a constructor injection to inject the repository into the controller class. This allows us to perform various database operations, such as saving and retrieving articles.
Then, let’s implement a POST endpoint to insert a record:
@PostMapping("/create-article")
private ResponseEntity<Article> createArticle(@RequestBody Article article, UriComponentsBuilder ucb) {
Article newArticle = new Article();
newArticle.setAuthor(article.getAuthor());
newArticle.setBody(article.getBody());
newArticle.setTitle(article.getTitle());
Article savedArticle = articleRepository.save(newArticle);
URI location = ucb.path("/articles/{id}").buildAndExpand(savedArticle.getId()).toUri();
return ResponseEntity.created(location).body(savedArticle);
}
In the code above, we create an endpoint that accepts an Article object as a request body and saves it to the database. Additionally, we return an HTTP 201 (Created) status.
5.3. Integration Test
Finally, let’s write an integration test using the RestTemplate class to verify the behavior of the POST request.
First, let’s create an integration test class:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ArticleApplicationIntegrationTest {
}
Next, let’s inject the RestTemplate instance:
@Autowired
TestRestTemplate restTemplate;
Then, let’s write a test method to send a POST request and verify the response:
@Test
void givenNewArticleObject_whenMakingAPostRequest_thenReturnCreated() {
Article article = new Article();
article.setTitle("Introduction to Java");
article.setAuthor("Baeldung");
article.setBody("Java is a programming language created by James Gosling");
ResponseEntity<Article> createResponse
= restTemplate.postForEntity("/create-article", article, Article.class);
assertThat(createResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED);
URI locationOfNewArticle = createResponse.getHeaders().getLocation();
ResponseEntity<String> getResponse
= restTemplate.getForEntity(locationOfNewArticle, String.class);
assertThat(getResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
}
In the code above, we assert that the record is successfully created and that retrieving it by id returns an HTTP 200 response.
6. Conclusion
In this article, we learned how to set up an IBM Db2 database and connect to it using the Db2 driver, configured in the application.properties file of a Spring Boot application. Additionally, we tested the connection by persisting a record to the database.
As always, the full source code for the examples is available over on GitHub.
The post Connect Java Spring Boot to Db2 Database first appeared on Baeldung.Image may be NSFW.Clik here to view.