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:

└──spark-java-hibernate-mysql-database-example
   ├──build.gradle
   └──src
      └──main
         ├──java
         │  └──com
         │     └──firstfewlines
         │        ├──model
         │        │  └──Task.java
         │        └──SparkJavaHibernateExample.java
         └──resources
            ├──hibernate.cfg.xml
            └──public
               └──index.html


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

mainClassName = 'com.firstfewlines.SparkJavaHibernateExample'

repositories {
    mavenCentral()
}

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'
}


2. Task.java

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;

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

    int id;
    String name;

    @Id
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


3. SparkJavaHibernateExample.java

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();

        staticFiles.location("/public");

        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();
                task.setId(id);
                task.setName(name);

                session.getTransaction().begin();
                session.persist(task);
                session.getTransaction().commit();

                res.redirect("/list");
                return "";
            } catch (Exception e) {
                return "Error: " + e.getMessage();
            } finally {
                if (session.isOpen()) {
                    session.close();
                }
            }
        });


        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" +
                        "</style>");


                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");
                }
                builder.append("</table>\n");

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

        });
    }
}


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

<hibernate-configuration>
    <session-factory>
        <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">
            org.hibernate.transaction.JDBCTransactionFactory
        </property>
        <property name="hbm2ddl.auto">update</property>

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

</hibernate-configuration>


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

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


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:


References:


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