Open In App
Related Articles

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

Improve Article
Save Article
Like Article

For the sample project, below mentioned tools got used

  • Java 8
  • Eclipse IDE for development
  • Hibernate ORM, Spring framework with Spring Data JPA
  • MySQL database, MySQL Connector Java as JDBC driver.

Example Project Using Spring Boot, MySQL, Spring Data JPA, and Maven

Project Structure:

Project Structure


As this is getting prepared as a maven project, all dependencies are specified in pom.xml



        <!--  Spring framework with support for Spring Data JPA -->
        <!--  Spring framework with support for Spring Data JPA -->
        <!-- MySQL dependency -->

As we are connecting with MySQL, we need to create the database and table for use in the project

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

CREATE TABLE `Contest` (
  `contestName` varchar(45) NOT NULL,
  `contestDescription` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)

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



<?xml version="1.0" encoding="UTF-8"?>
    <!-- Change the username and password with appropriate values -->
    <persistence-unit name="GeeksDB">
            <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" />

Configuration of EntityManagerFactory and TransactionManager


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

Let’s implement the model class.


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
// It maps with db table Contest
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.
    @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) { = 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;
    public String toString() {
        return "Contest [contestName=" + contestName + ", contestDescription=" + contestDescription + "]";

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.


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


import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
public class ContestService {
    private ContestRepository contestRepository;
    public void test() {
        // Save a new contest
        Contest geekContest = new Contest();
        geekContest.setContestDescription("Inviting Geeks To submit articles in plenty");
        // 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);

We can test the same via a test file


import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ContestTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();
        ContestService contestService = (ContestService) appContext.getBean("contestService");

We can run the test file as an ordinary Java application




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. 

Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated : 31 Oct, 2022
Like Article
Save Article
Similar Reads
Complete Tutorials