Setting up JPA on a Java Web App with MySQL deployed on Tomcat using IntelliJ as IDE with maven build.

In this post I will try to explain how JPA can be set up.

First we need a database that we will connect to. Make sure you are running MySQL in your environment.

Create a database called "learningjpa" and a table called "example" as follows:


Above I tried to show the steps from the command line. I have also added a row with "test" value to the table.

The table data also has a field "id" which is the Primary Key. We must provide this as this will be required by JPA.

Now as the second step create a maven project. I explained the steps in:
http://latenightjava.blogspot.com/2013/10/hello-world-web-application-with-maven.html
I will also use the source code from this project. So please download the file from that page and extract it to a folder you like. I have downloaded the source code to C:\Development\learningjpa


Now I will open up IntelliJ and import this project...
As I like to do I will keep project files in C:\Development\learningjpa-files

This is what the project looks like currently:


Now the first thing we need is an Implementation for JPA as JPA is only a specification. I will use Hibernate as the implementation. In order to use classes from Hibernate, we will need to add the dependencies to our pom.xml so the .jar files can be downloaded by maven when the project is built.

Add these to pom.xml:


Now, under resources folder create a file called META-INF and create a file called: persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
    <persistence-unit name="Persistence">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/learningjpa"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="password"/>
        </properties>
    </persistence-unit>
</persistence>

In persistence.xml, copy what you see above. of course, use your own user and password.
We also need the JDBC connector so add this dependency in pom.xml as well:
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

Now we need an "Entity" class.

This is what my Example.java in com\mywebapp\helloworld\Example.java looks like
package com.mywebapp.hello;
 
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name = "example")
public class Example {
 
    @Id
    private int ID;
 
    public int getID() {
        return ID;
    }
 
    public void setID(int ID) {
        this.ID = ID;
    }
 
    @Basic
    private String data;
 
    public String getData() {
        return data;
    }
 
    public void setData(String data) {
        this.data = data;
    }
}

Here you can see that we have provided the @Entity and the @Table annotations.

Now in persistence.xml, just above properties tag add this:
<class>com.mywebapp.hello.Example</class>

We are almost ready.

In HelloServlet.java, lets get the data from the database and show it to user.
package com.mywebapp.hello;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
 
public class HelloServlet extends HttpServlet {
 
    public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws IOException {
 
        EntityManagerFactory entityManagerFactory =
                Persistence.createEntityManagerFactory("Persistence");
 
        EntityManager em = entityManagerFactory.createEntityManager();
 
        TypedQuery<Example> exampleTypedQuery
                = em.createQuery("SELECT e FROM Example e", Example.class);
        List<Example> exampleList = exampleTypedQuery.getResultList();
        httpServletResponse.getWriter().print(exampleList.iterator().next().getData());
 
    }
}

Now run mvn clean install from command line where you have the pom file to this project. Notice that a folder with name target has been created. Now copy the war file in this directory to "webapps" folder under where you have Tomcat and then in "bin" folder run startup and then visit localhost:8080/my-webapp/hello

Now all you have to do is to visit localhost:8080/my-webapp/hello

As you can see data is fetched from the database.

Some bullet-points:
  • You need an @ID annotation to work with JPA. So at least one field must be @ID in your table.
  • JPA is about classes annotated with @Entity basically.
  • You need a persistence.xml. This is used in
EntityManagerFactory entityManagerFactory = 
    Persistence.createEntityManagerFactory("Persistence");