Spark Java with Hibernate and MySql database example

In practical scenario it is very common to integrate a database with the web service application. Here we will see an example to use Hibernate to store and retrieve data in Spark Java application. We will use MySql database behind the Hibernate.

The application provides HTML based UI for entering and viewing data.

Gradle is our build tool here. In case Maven is your favourite build tool, just let me know. I would be happy to create a pom.xml for you.

Source code folder structure:

         │  └──com
         │     └──firstfewlines
         │        ├──model
         │        │  └──
         │        └──

1. build.gradle
apply plugin: 'application'
apply plugin: 'java'
apply plugin: 'idea'

mainClassName = 'com.firstfewlines.SparkJavaHibernateExample'

repositories {

dependencies {
    compile 'com.sparkjava:spark-core:2.6.0'
    compile 'org.slf4j:slf4j-simple:1.7.25'
    compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.10.Final'
    runtime group: 'mysql', name: 'mysql-connector-java', version: '5.1.42'


This is our domain class to represent table: task_mst in the underlying database.

package com.firstfewlines.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name="task_mst", schema = "public")
public class Task {

    int id;
    String name;

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;


The main entry point of the application. Here we initialize all the needed components i.e the hibernate session, Spark Java static files location in resource and the web service end points.

package com.firstfewlines;

import static spark.Spark.*;

import com.firstfewlines.model.Task;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import javax.persistence.EntityManager;
import javax.servlet.MultipartConfigElement;
import java.util.List;

public class SparkJavaHibernateExample {

    public static void main(String[] argv) {

        SessionFactory sf = new Configuration().configure().buildSessionFactory();


        post("/api/task", (req, res) -> {

            EntityManager session = sf.createEntityManager();
            try {
                req.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement(""));

                Integer id = Integer.parseInt(req.queryParams("id"));
                String name = req.queryParams("name");

                Task task = new Task();


                return "";
            } catch (Exception e) {
                return "Error: " + e.getMessage();
            } finally {
                if (session.isOpen()) {

        get("/list", (req, res) -> {
            EntityManager session = sf.createEntityManager();
            try {
                List<Task> tasks = session.createQuery("FROM Task").getResultList();

                StringBuilder builder = new StringBuilder();

                builder.append("<style>\n" +
                        "table {\n" +
                        "    border-collapse: collapse;\n" +
                        "    width: 50%;\n" +
                        "}" +
                        "td, th {\n" +
                        "    border: 1px solid #dddddd;\n" +
                        "    text-align: left;\n" +
                        "    padding: 8px;\n" +
                        "}\n" +

                builder.append("<table><tr><th>Task Id</th><th>Task Name</th></tr>\n");
                for (Task task : tasks) {
                    builder.append("<tr><td>" + task.getId() + "</td><td>" + task.getName() + "</td></tr>\n");

                return builder.toString();
            } catch (Exception e) {
                return "Error: " + e.getMessage();
            } finally {
                if (session.isOpen()) {


4. hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"

        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="dialect">org.hibernate.dialect.MySQL57Dialect</property>
        <property name="hibernate.connection.username">test</property>
        <property name="hibernate.connection.password">test123</property>
        <property name="show_sql">true</property>
        <property name="transaction.factory_class">
        <property name="">update</property>

        <mapping class="com.firstfewlines.model.Task" />


5. index.html
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title> - SparkJava Hibernate example</title>
<h2> - SparkJava Hibernate example</h2>
<div style="display:block">
    <form method="post" action="/api/task" enctype="multipart/form-data">
                <td><label for="id">id:</label></td>
                <td><input type="number" id="id" name="id"/></td>

                <td><label for="name">Name:</label></td>
                <td><input type="text" id="name" name="name"/></td>
                <td colspan="2" style="text-align: right;">
                    <input type="submit" value="Save"/>

Download complete source code:

How to run the application?

  • First install and/or configure your MySql database to match the hibernate configuration.
  • Make sure you have latest version of Gradle installed and PATH is configured.
  • Download the attached source code zip file and unzip it to your local folder.
  • Go to the directory where you unzipped the file i.e. where the build.gradle is there
  • Run gradle clean bootRun command

Alternatively, you can use IntelliJ IDEa or Eclipse to import the Gradle project and run from there.

How to test:


Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus