<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vitor Fernandes on Medium]]></title>
        <description><![CDATA[Stories by Vitor Fernandes on Medium]]></description>
        <link>https://medium.com/@vitor.f?source=rss-68139ca3a263------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l1h6af8ZTeOtNWdhuCtCYQ.jpeg</url>
            <title>Stories by Vitor Fernandes on Medium</title>
            <link>https://medium.com/@vitor.f?source=rss-68139ca3a263------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:44:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vitor.f/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simplify Database Migrations with Flyway, Spring Boot, and Gradle]]></title>
            <link>https://medium.com/@vitor.f/simplify-database-migrations-with-flyway-spring-boot-and-gradle-45f1284c4877?source=rss-68139ca3a263------2</link>
            <guid isPermaLink="false">https://medium.com/p/45f1284c4877</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[flyway]]></category>
            <category><![CDATA[database-migration]]></category>
            <dc:creator><![CDATA[Vitor Fernandes]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 17:50:39 GMT</pubDate>
            <atom:updated>2025-01-21T17:50:39.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPkV8sLItvh4ZDrg1f_z9A.jpeg" /></figure><h3>Introduction</h3><p>Database migrations are the backbone of maintaining a healthy, evolving application. They ensure that as your software grows, the underlying database schema remains consistent, synchronised, and up-to-date across all environments — whether it’s development, testing, or production. By automating schema updates, migrations reduce the risk of human error, facilitate collaboration in team settings, and offer the crucial ability to roll back changes if something goes wrong. However, when migrations are handled improperly, they can lead to data loss, broken functionality, and costly downtime. These challenges underscore the importance of managing database migrations with care, as they are essential for the safe, efficient, and consistent evolution of your application.</p><h3>Why Choose Flyway for Database Migrations?</h3><p>So, what exactly is <a href="https://www.red-gate.com/products/flyway/">Flyway</a>? It’s an open-source database migration tool that takes the headache out of database migrations by automating the versioning, application, and tracking of every change to your schema.</p><p>In comparison with other database migration tools, flyway has:</p><ul><li><strong>Broad Database Support</strong>: Flyway supports a wide range of databases, including popular ones like PostgreSQL, MySQL, Oracle, and SQL Server.</li><li><strong>Simplicity and Ease of Use</strong>: Flyway is known for its straightforward setup and minimal configuration, allowing developers to quickly integrate it into their workflow without a steep learning curve.</li><li><strong>Version Control Integration</strong>: Flyway works seamlessly with version control systems like Git, enabling easy tracking and rollback of database changes alongside application code.</li><li><strong>Migration Agnosticism</strong>: Flyway is agnostic to the type of migration scripts it runs, allowing developers to use SQL, Java, or even command-line scripts, offering flexibility in how migrations are implemented.</li><li><strong>Strong Community and Documentation</strong>: Flyway has an active community and accessible documentation, providing resources and support for troubleshooting and best practices.</li></ul><p>Flyway simplifies database migrations by using filenames to manage version control. Upon its first run, Flyway creates a table called flyway_schema_history, which tracks the current state of your database. Each migration file is named according to a versioning system, allowing Flyway to apply and track changes systematically. This versioning not only ensures that your database schema evolves smoothly but also supports various migration functionalities, such as baseline versions, repeatable migrations, and error handling, providing a framework for maintaining consistency and control over your database updates (<a href="https://documentation.red-gate.com/fd/concepts-184127447.html">flyway concepts</a>).</p><p>Here are some examples of how to name your Flyway migration files:</p><ul><li>Version migration <em>(Used for changes that are applied in a specific version sequence)</em>: <strong><em>V1_0_0__initial_migration.sql</em></strong></li><li>Undo version migration <em>(For rolling back changes in a specific version; note this is available in Flyway’s commercial edition)</em>: <strong><em>U1_0_0__initial_migration.sql</em></strong></li><li>Repeatable migration <em>(For changes that should be reapplied every time the migration script is run)</em>: <strong><em>R__example.sql</em></strong></li></ul><p>For a deeper dive into the ins and outs of database migrations and how to take advantage of the Flyway, I recommend you explore the following documentation. It provides information and guidance to help you master the Flyway’s functionalities.</p><p><a href="https://documentation.red-gate.com/fd/migrations-184127470.html">Migrations</a></p><h3><strong>Configuring Flyway in Spring Boot</strong></h3><p>Managing database migrations in a Spring Boot project can feel intimidating, but thanks to Flyway, the process becomes seamless and stress-free. Flyway integrates effortlessly with Spring Boot, allowing you to maintain a versioned history of your database schema with minimal effort.</p><p>Getting started is a breeze. First, add the necessary Gradle dependencies. At a minimum, you’ll need the Flyway Core dependency to power the migrations. Since we’re working with a PostgreSQL database, don’t forget to include Flyway’s PostgreSQL-specific support dependency.</p><pre>implementation &quot;org.flywaydb:flyway-core&quot;<br>runtimeOnly &quot;org.flywaydb:flyway-database-postgresql&quot;</pre><p>With these in place, you’re all set to dive into the configuration steps and unlock the full potential of automated database migrations in your project.</p><p>It’s time to configure your application to leverage Flyway’s full capabilities. With just a few tweaks in your <strong>application.properties</strong>, you can ensure your database schema is always up-to-date.</p><p>First, set up Flyway to validate the database schema on each application startup. If the database is on an older migration version, Flyway will automatically apply the necessary migrations to bring it up to the latest version.</p><p>Next, we’ll enable Flyway in Spring Boot by adding the JDBC connection details, including the database URL, username, and password. Lastly, we specify the location of the migration scripts. In my case, this is under <strong>src/main/resources/db/migration</strong>, represented in the properties file as <strong>classpath:db/migration</strong>.</p><pre># Enables Flyway in Spring<br>spring.flyway.enabled=true<br># Connection details<br>spring.flyway.url=jdbc:postgresql://localhost:5432/db_name<br>spring.flyway.user=username<br>spring.flyway.password=password<br># Fyway migration files location<br>spring.flyway.locations=classpath:db/migration</pre><p>With these configurations in place, simply run your Spring Boot application and let Flyway seamlessly handle your database migrations. Every time your application starts, Flyway ensures your database schema is always in sync with your code — no manual intervention needed.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, Flyway is an essential tool for simplifying database migrations in Spring Boot applications. With just a few straightforward configurations, it provides a seamless way to keep your database schema in sync with your application. Say goodbye to manual scripts and versioning headaches — Flyway handles it all, allowing you to focus on building features and driving innovation. By incorporating Flyway, you’re not just optimising your workflow; you’re setting the stage for a more efficient and reliable database management process. Ready to take your development to the next level? Let Flyway handle the rest!</p><blockquote><em>Thank you for reading this article. Happy coding! 🚀💻</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45f1284c4877" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration Testing with Spring Boot and Testcontainers: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@vitor.f/integration-testing-with-spring-boot-and-testcontainers-a-step-by-step-guide-8b32a8dcce98?source=rss-68139ca3a263------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b32a8dcce98</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Vitor Fernandes]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 09:38:35 GMT</pubDate>
            <atom:updated>2024-08-19T09:38:35.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0xix0OQGKBffC1bv" /></figure><h3>1. Introduction</h3><p>As software grows and evolves, automated testing shifts from a luxury to an absolute necessity. Unit tests shine at ensuring each piece of the puzzle functions independently, but they can’t guarantee that the whole picture comes together perfectly. So, how do we make sure everything runs smoothly without manually testing every feature after every update? Enter integration tests — your secret weapon for making sure all components work in harmony, so you can deploy with confidence, knowing your application is rock-solid from end to end.</p><h3>2 . Why use Testcontainers?</h3><h4>The Problem:</h4><p>Running integration tests often means ensuring that the entire infrastructure — databases, message brokers, and other services — is not only up and running but also pre-configured to a specific state. However, when these resources are shared across multiple users or CI pipelines, test results can become unpredictable due to issues like data corruption and configuration drift. While some developers attempt to bypass these challenges with in-memory databases, embedded services, or mocks, these solutions introduce their own set of problems. In-memory services, for instance, may lack critical features or behave differently from their production counterparts, leading to false positives and negatives in test outcomes.</p><h4>The Solution:</h4><p>This is where Testcontainers comes into play. Testcontainers allows you to run your application’s dependencies, such as databases and message brokers, in isolated Docker containers, creating a consistent and reliable environment for your integration tests. By interacting with these real services instead of mock or in-memory alternatives, Testcontainers ensures that your tests are as close to the production environment as possible. This not only eliminates the unpredictability caused by shared resources but also provides a programmatic API that makes it easy to manage and control these containers within your test code. The result is more accurate, repeatable tests that give you confidence your application will behave as expected in the real world.</p><p><a href="https://testcontainers.com/getting-started/">Getting Started</a></p><h3>3 . Create a Simple Spring Boot Application</h3><p>Before we dive into writing integration tests with Testcontainers and Spring Boot, let’s start by building the application we’ll be testing. And where better to kick things off than at every Spring developer’s favourite playground — the Spring Initializr! 🎉</p><p><a href="https://start.spring.io/">Spring Initializr</a></p><p>For our example, we’ll keep things straightforward: a simple controller that connects to a repository and stores books in a PostgreSQL database. We’ll be using Java 21, Gradle with Groovy, and the latest Spring Boot 3.3.2 — keeping it fresh and modern as of this writing. 📚✨</p><p>To get our project up and running, let’s sprinkle in some magic with these must-have dependencies in your <strong>build.gradle</strong> file:</p><pre>implementation &#39;org.springframework.boot:spring-boot-starter&#39;<br>implementation &#39;org.springframework.boot:spring-boot-starter-data-jpa&#39;<br>implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>implementation &quot;org.apache.httpcomponents.client5:httpclient5&quot;<br><br>runtimeOnly &#39;org.postgresql:postgresql&#39;<br><br>compileOnly &#39;org.projectlombok:lombok&#39;<br>annotationProcessor &#39;org.projectlombok:lombok&#39;<br><br>testCompileOnly &#39;org.projectlombok:lombok&#39;<br>testAnnotationProcessor &#39;org.projectlombok:lombok&#39;<br><br>testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>testImplementation &#39;org.springframework.boot:spring-boot-testcontainers&#39;<br>testImplementation &#39;org.testcontainers:junit-jupiter&#39;<br>testImplementation &#39;org.testcontainers:postgresql&#39;<br>testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;</pre><p>Here’s how we’re going to lay out our project — think of it as the blueprint for building our book-storing application:</p><pre>.<br>└── controller/                      <br>│   ├── dto/                         <br>│   │    └── BookDto.java           // Book data transfer object<br>│   ├── BookController.java         // The Application entry point<br>│   └── database                     <br>│       ├── dao<br>│       │   └── Book.java           // The book database entity<br>│       └── BookRepository.java     // The book repository<br>│<br>├── build.gradle                    // Project configuration and settings<br>└── application.properties          // Application properties configuration</pre><p>We’ll kick things off with the <strong>Book</strong> class, which will serve as our database entity. It’s a simple yet essential structure, featuring an <strong>id</strong>, <strong>author</strong>, and <strong>title</strong> — just what we need to start storing our books.</p><pre>@Entity<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Data<br>@Builder<br>public final class Book {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.AUTO)<br>    private Long id;<br>    @Column(nullable = false)<br>    private String title;<br>    @Column(nullable = false)<br>    private String author;<br>}</pre><p>With the <strong>Book</strong> class in place, it’s time to create the <strong>BookRepository</strong> to handle our database interactions. We’ll keep it simple by extending <strong>JpaRepository</strong>, giving us a powerful and streamlined way to manage our book data. Here’s how it will look:</p><pre>public interface BookRepository extends JpaRepository&lt;Book, Long&gt; {<br>}</pre><p>With our database classes in place, it’s time to configure our application. Add the following properties to your <strong>application.properties</strong> file to seamlessly integrate with our setup. For reference, the GitHub repo includes a Docker Compose file that sets up a PostgreSQL container with these connection properties:</p><pre>spring.application.name=book<br>server.port=8080<br><br>spring.datasource.url=jdbc:postgresql://localhost:5432/bookdb<br>spring.datasource.username=bookUser<br>spring.datasource.password=password<br><br>spring.jpa.hibernate.ddl-auto=create-drop</pre><p>Next up is our application’s entry point: the <strong>BookController</strong>. This will be a <strong>RestController</strong> with the <strong>/books</strong> request path. To keep things concise, I’ll show just the <strong>createBook</strong> method here, but you can check out my GitHub page for the full code. The controller is straightforward, with <strong>BookRepository</strong> as a dependency and basic validations, like checking if a book exists when fetching all books or ensuring the book has a title and author when creating a new one. Here’s how it looks:</p><pre>@Slf4j<br>@RestController<br>@RequestMapping(&quot;/books&quot;)<br>@RequiredArgsConstructor<br>final class BookController {<br><br>    private final BookRepository bookRepository;<br><br>    @PostMapping<br>    ResponseEntity&lt;Void&gt; createBook(@RequestBody final BookDto bookDto) {<br>        try {<br><br>            if (!StringUtils.hasText(bookDto.getTitle()) || !StringUtils.hasText(bookDto.getAuthor())) {<br>                log.warn(&quot;Invalid book data: {}&quot;, bookDto);<br>                return ResponseEntity.badRequest().build();<br>            }<br><br>            final var book = new Book(null, bookDto.getTitle(), bookDto.getAuthor());<br><br>            bookRepository.save(book);<br>            log.info(&quot;Book created: {}&quot;, book);<br><br>            return ResponseEntity.status(HttpStatus.CREATED).build();<br>        } catch (RuntimeException exception) {<br>            log.error(&quot;Error creating book&quot;, exception);<br>            return ResponseEntity.internalServerError().build();<br>        }<br><br>    }<br><br>}</pre><p>As you might notice, the controller interacts with a <strong>BookDto</strong> instead of directly using the <strong>Book</strong> entity. This <strong>BookDto</strong> serves as a lightweight copy of the <strong>Book</strong> object, helping us keep the separation between the backend and frontend. Here’s what the <strong>BookDto</strong> looks like:</p><pre>@AllArgsConstructor<br>@Getter<br>@Setter<br>@EqualsAndHashCode<br>@JsonInclude(JsonInclude.Include.NON_NULL)<br>public class BookDto {<br>    private Long id;<br>    private String title;<br>    private String author;<br>}</pre><h3>4. Writing integration tests with Testcontainers</h3><p>Now that we’ve got our application up and running, it’s time to take things to the next level with integration tests using Testcontainers. With the Testcontainers dependency already in place, we’re all set to dive into creating robust tests that will ensure our application runs smoothly. First, make sure <strong>Docker</strong> is running, as Testcontainers relies on it to create and manage containers at runtime. Then, let’s get started! 🚀📦</p><p>To kick things off, we’ll set up a custom PostgreSQL container. While you could pull one directly from a Docker image, I prefer crafting custom classes to have more control over our containers. We’ll create a singleton class that extends Testcontainers’ <strong>PostgreSQLContainer</strong>, giving us an adapted setup. Here’s what our custom container looks like:</p><pre>public final class BookPostgresqlContainer extends PostgreSQLContainer&lt;BookPostgresqlContainer&gt; {<br><br>    private static final String IMAGE_VERSION = &quot;postgres:latest&quot;;<br>    private static BookPostgresqlContainer container;<br><br>    private BookPostgresqlContainer() {<br>        super(IMAGE_VERSION);<br>    }<br><br>    public static BookPostgresqlContainer getInstance() {<br>        if (container == null) {<br>            container = new BookPostgresqlContainer();<br>        }<br>        return container;<br>    }<br><br>    @Override<br>    public void start() {<br>        super.start();<br>    }<br><br>}</pre><p>With our container set up, we’re ready to dive into writing tests. Personally, I prefer to keep configuration separate from the test logic. So, we’ll start by creating a <strong>BaseIntegrationTest</strong> class to handle the setup, and then build out the <strong>CreateBookTest</strong> class that extends it. This approach keeps things clean and organized. Let’s get started! 🚀🧪</p><p>The <strong>BaseIntegrationTest</strong> class serves as our foundation, running a PostgreSQL container with the power of <a href="http://twitter.com/SpringBootTest"><strong>@SpringBootTest</strong></a>. Before any tests kick off, we’ll set up Spring’s <strong>RestTemplate</strong> to perform REST requests to our Spring Boot application. This will allow us to interact with our API just like a real user would. Additionally, we’ll start the <strong>PostgreSQLContainer</strong>, which will serve as the database for our application during testing. A key player here is the <a href="http://twitter.com/Testcontainers"><strong>@Testcontainers</strong></a> annotation, which ensures that all fields annotated with <a href="http://twitter.com/Container"><strong>@Container</strong></a> are managed properly — taking care of the lifecycle of our PostgreSQL container.</p><p>Next, we’ll configure our application properties to leverage the data from our container, including the username, password, and JDBC URL. This is done with the <a href="http://twitter.com/DynamicPropertySourc"><strong>@DynamicPropertySourc</strong></a><strong>e</strong> annotation from Spring, which allows us to dynamically inject these properties at runtime, ensuring that our application seamlessly connects to the containerised database during tests.</p><p>This setup keeps everything running smoothly and ready for action! 🌟🔧</p><pre>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)<br>@AutoConfigureMockMvc<br>@DirtiesContext<br>@Testcontainers<br>public class BaseIntegrationTest {<br><br>    @Container<br>    protected static final PostgreSQLContainer&lt;BookPostgresqlContainer&gt; postgreSQLContainer = BookPostgresqlContainer.getInstance();<br>    protected static RestTemplate restTemplate;<br>    @LocalServerPort<br>    protected Integer port;<br><br>    @DynamicPropertySource<br>    static void registerDynamicProperties(final DynamicPropertyRegistry registry) {<br>        registry.add(&quot;spring.datasource.url&quot;, postgreSQLContainer::getJdbcUrl);<br>        registry.add(&quot;spring.datasource.username&quot;, postgreSQLContainer::getUsername);<br>        registry.add(&quot;spring.datasource.password&quot;, postgreSQLContainer::getPassword);<br>        registry.add(&quot;spring.datasource.driver-class-name&quot;, postgreSQLContainer::getDriverClassName);<br>    }<br><br>    @BeforeAll<br>    protected static void setup() {<br>        postgreSQLContainer.start();<br><br>        restTemplate = new RestTemplate();<br>        final HttpClient httpClient = HttpClientBuilder.create().build();<br>        final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);<br>        restTemplate.setRequestFactory(requestFactory);<br>    }<br><br>    @AfterAll<br>    protected static void tearDown() {<br>        postgreSQLContainer.stop();<br>    }<br><br>}</pre><p>For our create-book integration tests, it’s as easy as extending the <strong>BaseIntegrationTest</strong> class to set up your configuration. Then, simply use <strong>RestTemplate</strong> to perform the requests. This approach keeps everything streamlined and your tests looking sharp. Check out the example below to see how effortlessly you can create clean and effective tests! 📚✨</p><pre>class CreateBookTest extends BaseIntegrationTest {<br><br>    private static final String AUTHOR_NAME = &quot;Author&quot;;<br>    private static final String BOOK_TITLE = &quot;Title&quot;;<br><br>    @Autowired<br>    private BookRepository bookRepository;<br><br>    @Test<br>    void createBookWithSuccess() {<br>        final var bookDto = new BookDto(null, BOOK_TITLE, AUTHOR_NAME);<br><br>        final var response = restTemplate.postForEntity(<br>                String.format(&quot;http://localhost:%d/books&quot;, port),<br>                bookDto,<br>                Void.class);<br><br>        assertEquals(HttpStatus.CREATED, response.getStatusCode());<br><br>        bookRepository.findById(1L).ifPresentOrElse(book -&gt; assertAll(<br>                () -&gt; assertEquals(BOOK_TITLE, book.getTitle()),<br>                () -&gt; assertEquals(AUTHOR_NAME, book.getAuthor())<br>        ), () -&gt; fail(&quot;Book not found&quot;));<br>    }<br><br>    @Test<br>    void errorCreatingBookNoTitle() {<br>        final var bookDto = new BookDto(null, null, AUTHOR_NAME);<br><br>        try {<br><br>            restTemplate.postForEntity(<br>                    String.format(&quot;http://localhost:%d/books&quot;, port),<br>                    bookDto,<br>                    Void.class);<br><br>        } catch (final HttpClientErrorException e) {<br>            assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode());<br>        }<br><br>    }<br><br>    @Test<br>    void errorCreatingBookNoAuthor() {<br>        final var bookDto = new BookDto(null, BOOK_TITLE, null);<br><br>        try {<br><br>            restTemplate.postForEntity(<br>                    String.format(&quot;http://localhost:%d/books&quot;, port),<br>                    bookDto,<br>                    Void.class);<br><br>        } catch (final HttpClientErrorException e) {<br>            assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode());<br>        }<br><br>    }<br><br>}</pre><h3>5. Conclusions</h3><p>In this article, we’ve explored the crucial role of integration tests in ensuring our applications run smoothly from end to end. By leveraging Testcontainers, we’ve seen how to streamline the testing process, providing a clean and controlled environment for our tests. This approach not only simplifies managing dependencies but also enhances the reliability of our test results. With integration tests and Testcontainers in your toolkit, you can confidently deploy your applications, knowing that every component is carefully controlled and ready for action.</p><blockquote>To check out the complete codebase and see everything in action, visit the GitHub repository page. Happy coding! <em>🚀💻</em></blockquote><blockquote><a href="https://github.com/VitorFernandes2/book">https://github.com/VitorFernandes2/book</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b32a8dcce98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>