Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – LSD – NPI (cat=JPA)
announcement - icon

Get started with Spring Data JPA through the reference Learn Spring Data JPA:

>> CHECK OUT THE COURSE

Partner – Microsoft – NPI (cat=Spring)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

eBook Jackson – NPI EA – 3 (cat = Jackson)