Skip to main content

Example of Maven project that interacts with a MySQL database and includes testing

Example Maven project that interacts with a MySQL database and includes testing

To install Java, MySQL, Maven, and write a Java program to fetch table data, execute, and create a JAR file using Maven on Ubuntu, you can follow these steps:

Step 1: Install Java

You can install Java using the following commands:

sudo apt update

sudo apt install default-jre

sudo apt install default-jdk

Verify the installation by running:

java -version

Step 2: Install MySQL

You can install MySQL using the following commands:

sudo apt update

sudo apt install mysql-server

During the installation, you'll be prompted to set a root password for MySQL or you can set password at latter stage using following steps. 

sudo mysql

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

exit


Step 3: Install Maven

You can install Maven using the following commands:

sudo apt update

sudo apt install maven

Verify the installation by running:

mvn -version




Step 4: Create a Maven Project

Open a command prompt or terminal and follow these steps to create a Maven project locally:


# Create a new directory for your project

mkdir MyDBProject

cd MyDBProject

# Create a new Maven project (using the `maven-archetype-quickstart` archetype)

mvn archetype:generate -DgroupId=com.example -DartifactId=db-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

The command you provided is a Maven command-line command used to generate a new Maven project from an archetype template. Let's break down the command and explain each part:

  • mvn: This is the Maven command-line tool used to execute various Maven goals and commands.
  • archetype:generate: This is a specific Maven goal provided by the archetype plugin. It tells Maven to generate a new project based on an archetype template.
  • -DgroupId=com.example: This is a system property (-D) that sets the groupId for the generated project. The groupId is typically used to uniquely identify your project within a group or organization. In this case, it's set to "com.example," but you can replace it with your desired group identifier.
  • -DartifactId=db-project: Similar to the groupId, this is another system property that sets the artifactId for the generated project. The artifactId is the name of the generated project. In this case, it's set to "db-project," but you can change it to the name you prefer for your project.
  • -DarchetypeArtifactId=maven-archetype-quickstart: This property specifies the archetype template to use for generating the project. In this case, it's using the "maven-archetype-quickstart" archetype, which is a commonly used archetype for generating a simple Java project structure. This archetype provides a basic project structure with source code directories and a sample Java class.
  • -DinteractiveMode=false: This property disables interactive mode during project generation. When set to "false," Maven won't prompt you for additional information, and it will use the default values specified for the archetype. If you omit this property or set it to "true," Maven will prompt you for information like the project version, package name, and more.
So, when you run this command, Maven will create a new project with the specified group and artifact IDs, based on the "maven-archetype-quickstart" archetype, and it will do so without asking for interactive input if you set -DinteractiveMode to "false." The generated project will have a basic directory structure for a Java project, including a sample Java source file and a default pom.xml file with project configuration.

You can then further customize this generated project to suit your specific development needs.



# Navigate to the project directory

cd db-project



Step 5: Define the Java Class for Database Interaction

Open the src/main/java/com/example/App.java file and replace its contents with a Java class for database interaction using JDBC and MySQL:


package com.example;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;


public class App {

    public static void main(String[] args) {

        String jdbcUrl = "jdbc:mysql://localhost:3306/yourdb";

        String username = "yourusername";

        String password = "yourpassword";


        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {

            String query = "SELECT * FROM yourtable";

            try (Statement statement = connection.createStatement();

                 ResultSet resultSet = statement.executeQuery(query)) {


                while (resultSet.next()) {

                    int id = resultSet.getInt("id");

                    String name = resultSet.getString("name");

                    System.out.println("ID: " + id + ", Name: " + name);

                }

            }

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

Replace "jdbc:mysql://localhost:3306/yourdb", "yourusername", and "yourpassword" with your MySQL database connection details.


Step 6: Create a Test Script

Create a test script in src/test/java/com/example/AppTest.java for testing your database interaction logic. For simplicity, you can create a test that ensures the database connection is established correctly.


package com.example;


import org.junit.jupiter.api.Test;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;


import static org.junit.jupiter.api.Assertions.*;


public class AppTest {

    @Test

    public void testDatabaseConnection() {

        String jdbcUrl = "jdbc:mysql://localhost:3306/yourdb";

        String username = "yourusername";

        String password = "yourpassword";


        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {

            assertNotNull(connection);

        } catch (SQLException e) {

            fail("Database connection failed");

        }

    }

}

Step 7: Define the pom.xml Script

Open the pom.xml file in the project root directory and replace its contents with the following pom.xml script. This script includes dependencies for JDBC and JUnit:


<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>


    <groupId>com.example</groupId>

    <artifactId>db-project</artifactId>

    <version>1.0-SNAPSHOT</version>


    <properties>

        <maven.compiler.source>1.8</maven.compiler.source>

        <maven.compiler.target>1.8</maven.compiler.target>

    </properties>


    <dependencies>

        <!-- JDBC for MySQL -->

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <version>8.0.27</version>

        </dependency>


        <!-- JUnit 5 dependencies -->

        <dependency>

            <groupId>org.junit.jupiter</groupId>

            <artifactId>junit-jupiter-api</artifactId>

            <version>5.8.2</version>

            <scope>test</scope>

        </dependency>

    </dependencies>


    <build>

        <plugins>

            <!-- Configure Compiler Plugin -->

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-compiler-plugin</artifactId>

                <version>3.8.0</version>

                <configuration>

                    <source>1.8</source>

                    <target>1.8</target>

                </configuration>

            </plugin>


            <!-- Configure JAR Plugin -->

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-jar-plugin</artifactId>

                <version>3.2.0</version>

                <configuration>

                    <archive>

                        <manifest>

                            <mainClass>com.example.App</mainClass>

                        </manifest>

                    </archive>

                </configuration>

            </plugin>


            <!-- Configure Surefire Plugin for running tests -->

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-surefire-plugin</artifactId>

                <version>2.22.2</version>

            </plugin>


            <!-- Configure Shade Plugin for creating an executable JAR with dependencies -->

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-shade-plugin</artifactId>

                <version>3.2.4</version> <!-- Adjust version as needed -->

                <executions>

                    <execution>

                        <phase>package</phase>

                        <goals>

                            <goal>shade</goal>

                        </goals>

                        <configuration>

                            <transformers>

                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">

                                    <mainClass>com.example.App</mainClass> <!-- Replace with your main class -->

                                </transformer>

                            </transformers>

                        </configuration>

                    </execution>

                </executions>

            </plugin>

        </plugins>

    </build>

</project>



Step 8: Build and Run the Project

Now, you can build and run your Maven project locally without Git or GitHub. Use the following command in your project directory:


mvn clean install

This will compile your code, execute the test script, and package your project.


Step 9: Verify the Results

Check the console output to ensure that your code executed correctly and that the test passed.

You've

Use the following command to run the project

java -jar target/db-project-1.0-SNAPSHOT.jar


GitHub Repo: https://github.com/antoshdyade/mavenmysqltest/tree/master/db-project



---

pom.xml Explanation

The pom.xml file you provided is the Project Object Model (POM) for a Maven-based Java project. It contains metadata and configuration information that Maven uses to build, test, and package your project. Let's break down the key elements and their meanings:

  1. project Element:
    • This is the root element of the POM file, and it defines the project's configuration.
  2. modelVersion Element:
    • Specifies the version of the POM model. In this case, it's set to 4.0.0, which is the current version.
  3. groupId, artifactId, and version Elements:
    • These elements define the basic project coordinates:
      • groupId: A unique identifier for your project's group or organization.
      • artifactId: The name of your project (in this case, "db-project").
      • version: The version of your project (e.g., "1.0-SNAPSHOT").
  4. properties Element:
    • This section allows you to define properties that can be reused in various parts of the POM. In this case, it sets the source and target Java versions to 1.8.
  5. dependencies Element:
    • This section lists the project's dependencies, which are external libraries or packages that your project relies on. Notable dependencies in this example:
      • mysql-connector-java: A MySQL JDBC driver used for database connectivity.
      • junit-jupiter-api: The JUnit 5 testing framework for writing and running tests.
  6. build Element:
    • Contains build-related configurations, including plugins for building and testing your project.
  7. maven-compiler-plugin:
    • Configures the Maven Compiler Plugin to compile your source code. It sets both the source and target Java versions to 1.8.
  8. maven-jar-plugin:
    • Configures the Maven JAR Plugin to package your project as a JAR file. It specifies a mainClass in the manifest, which is the entry point of your application. You should replace com.example.App with the actual main class of your application.
  9. maven-surefire-plugin:
    • Configures the Maven Surefire Plugin, which is used for running tests. In this section, the plugin is configured with its version (2.22.2).
  10. maven-shade-plugin:
    • Configures the Maven Shade Plugin, which is used for creating an executable JAR file that includes all project dependencies (a "fat JAR"). This allows you to distribute a self-contained application.
    • The <mainClass> element within the transformer configuration specifies the main class to be used when running the JAR. You should replace com.example.App with your actual main class.

Overall, this pom.xml file is designed to build a Java project, compile its source code, run tests, package it as an executable JAR file with dependencies included, and specify the entry point of the application. You can use this configuration as a starting point for Maven-based Java projects and customize it further based on your project's needs.

Comments

Popular posts from this blog

Maven Create and Build Artifacts

In Maven, you can create and build artifacts using the package phase of the build lifecycle. The package phase is responsible for taking the compiled code and other project resources and packaging them into a distributable format, such as a JAR (Java Archive), WAR (Web Application Archive), or other custom formats. Here are the steps to create and build artifacts using Maven: Configure the Build Output: In your project's pom.xml file, you need to configure the output of the build. This includes specifying the type of artifact you want to create (e.g., JAR, WAR) and any additional resources to include. You do this in the <build> section of your pom.xml: <build>     <finalName>my-artifact</finalName> <!-- Name of the artifact without the extension -->     <plugins>         <!-- Plugin configurations for creating the artifact -->         <!-- For example, maven-jar-plugin or maven-war-p...

Maven Repositories (local, central, global)

Maven relies on repositories to manage dependencies, plugins, and other artifacts required for a project. There are typically three types of repositories in Maven: local, central, and remote/global repositories. Local Repository: Location: The local repository is located on your local development machine. By default, it's in the .m2 directory within your user home directory (e.g., C:\Users\<username>\.m2\repository on Windows or /Users/<username>/.m2/repository on macOS and Linux). Purpose: The local repository is used to store artifacts (JARs, POMs, and other files) that your machine has downloaded or built during previous Maven builds. These artifacts are specific to your local development environment. Benefits: Using a local repository improves build performance since it caches dependencies locally, reducing the need to download them repeatedly. It also ensures reproducibility by maintaining a local copy of dependencies. Central Repository: Location: The central repo...