How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?

Last Updated : 30 Mar, 2026

Spring Boot, along with Spring Data JPA and MySQL, provides a powerful stack for building robust backend applications. Maven is used for dependency management and project build automation, making development faster and more organized.

  • Simplifies backend development using Spring Boot
  • Uses Spring Data JPA for database operations without boilerplate code
  • Integrates MySQL for persistent data storage

Prerequisites

Before starting, ensure you have:

Step-by-Step Implementation

Step 1: Create Maven Project

Create a Maven project and define dependencies in pom.xml.

Project Structure:

Project Structure
 

pom.xml

XML
<project xmlns="https://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 
                             https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.gfg</groupId>
    <artifactId>SpringDataJPAConsoleSample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
     <maven.compiler.source>1.8</maven.compiler.source>
     <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <!--  Spring framework with support for Spring Data JPA -->
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>
        <!--  Spring framework with support for Spring Data JPA -->
        <!-- MySQL dependency -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.14</version>
        </dependency>
    </dependencies>
</project>

Step 2: Create Database and Table

Run the following SQL commands:

create database geeksforgeeks; # Creation
use geeksforgeeks #Make the database active

CREATE TABLE `Contest` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`contestName` varchar(45) NOT NULL,

`contestDescription` varchar(45) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

Step 3: Configure Database Connection

Database connection properties are set in src/main/resources/persistence.xml 

persistence.xml 

XML
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/index.html"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/index.html
          http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/index.html/persistence_2_1.xsd"
    version="2.1">
    <!-- Change the username and password with appropriate values -->
    <persistence-unit name="GeeksDB">
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/geeksforgeeks?useSSL=false" />
            <property name="javax.persistence.jdbc.user" value="***" />
            <property name="javax.persistence.jdbc.password" value="***" />
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
        </properties>
    </persistence-unit>
    
</persistence>

Step 4: Configure JPA (EntityManager & Transaction Manager)

Configuration of EntityManagerFactory and TransactionManager

ContestAppConfig.java

Java
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;

@Configuration 
// Scan the repositories that is present under com.gfg.jpa
@EnableJpaRepositories(basePackages = {"com.gfg.jpa"})
public class ContestAppConfig {
    @Bean
    // LocalEntityManagerFactoryBean sets up an EntityManagerFactory to work with GeeksDB
    public LocalEntityManagerFactoryBean entityManagerFactory() {
        LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
        factoryBean.setPersistenceUnitName("GeeksDB");        
        return factoryBean;
    }
    
    @Bean
    // Transaction manager for the configured EntityManagerFactory,
    public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);        
        return transactionManager;
    }    
}

Step 5: Create Entity Class

Let's implement the model class.

Contest.java

Java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

// It maps with db table Contest
@Entity
public class Contest {
    // The @Id and @GeneratedValue annotations map 
      // the field id to the primary key column of the table. 
      // Suppose that all the fields of the class have
      // same name as the column names in the database table.
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String contestName;
    private String contestDescription;

    protected Contest() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
    
    public String getContestName() {
        return contestName;
    }

    public void setContestName(String contestName) {
        this.contestName = contestName;
    }

    public String getContestDescription() {
        return contestDescription;
    }

    public void setContestDescription(String contestDescription) {
        this.contestDescription = contestDescription;
    }

    @Override
    public String toString() {
        return "Contest [contestName=" + contestName + ", contestDescription=" + contestDescription + "]";
    }

}

Step 6: Create Repository Interface

Instead of writing a generic DAO class, a simple interface like below is enough. It extends CrudRepository defined by Spring Data JPA. Common CRUD operations like  save(), findAll(), findById(), delete(), count() etc., are defined by the interface.

ContestRepository.java

Java
import java.util.List;
import org.springframework.data.repository.CrudRepository;

public interface ContestRepository extends CrudRepository<Contest, Long> {
    // We can add the required methods here
    List<Contest> findByContestName(String contestName);
}

Step 7: Create Service Layer

Java
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("contestService")
public class ContestService {
  
    @Autowired
    private ContestRepository contestRepository;
    
    public void test() {
        // Save a new contest
        Contest geekContest = new Contest();
        geekContest.setContestName("PremierLeague");
        geekContest.setContestDescription("Inviting Geeks To submit articles in plenty");
        
        contestRepository.save(geekContest);
        
        // Find a contest by ID
        Optional<Contest> result = contestRepository.findById(1L);
        result.ifPresent(contest -> System.out.println(contest));
        
        // Find contest by contest name
        List<Contest> contests = contestRepository.findByContestName("PremierLeague");
        contests.forEach(contest -> System.out.println(contest));
        
        // List all contests
        Iterable<Contest> iterator = contestRepository.findAll();
        iterator.forEach(contest -> System.out.println(contest));
        
        // Count number of contest
        long countOfContest = contestRepository.count();
        System.out.println("Number of contest held: " + countOfContest);
    }
}

Step 8: Create Test Class

ContestTest.java

Java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ContestTest {
  
    public static void main(String[] args) {
      
        AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();
        appContext.scan("com.gfg.jpa");
        appContext.refresh();

        ContestService contestService = (ContestService) appContext.getBean("contestService");
        contestService.test();

        appContext.close();
      
    }

}

Step 9: Run the Application

  • Run ContestTest.java as a Java application
  • Data will be inserted and retrieved from MySQL

Output:

Output
 

As we have tested via contestname as well, in the first output, we saw that one contest got inserted and the same is getting used to test while testing via contestname

 

We can check the DB data also

Database Output

Note: id field is auto-generated. 

Comment