Simple CRUD REST API with Java EE

by Hayri Cicek

Posted on 02-Aug-2018

In this tutorial we will learn how to create a simple CRUD REST API with Java EE using H2 database and TomEE application server.
H2 is an open source relational database management system written in Java. It can be embedded in Java applications or run in the client-server mode and it is easy to install and deploy.

Tools You Will Need
Maven 3.3+
Your favorite IDE. I'm using NetBeans
JDK 1.8+

Create the Directory Structure
The first thing is to create a directory where we will have our project source files.
Open your terminal and create the directories and the files

$ mkdir simple-javaee-crud-rest-api
$ mkdir -p src/main/java/com/kodnito/restapi/models
$ mkdir -p src/main/java/com/kodnito/restapi/dao
$ mkdir -p src/main/java/com/kodnito/restapi/resources
$ mkdir -p src/main/resources/META-INF
$ mkdir -p src/main/webapp/WEB-INF
$ touch src/main/webapp/WEB-INF/resources.xml
$ touch src/main/resources/META-INF/persistence.xml
$ touch src/main/java/com/kodnito/restapi/models/
$ touch src/main/java/com/kodnito/restapi/dao/
$ touch src/main/java/com/kodnito/restapi/resources/
$ touch src/main/java/com/kodnito/restapi/resources/
$ touch pom.xml

Your directory structure should look like this
$ tree
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── kodnito
        │           └── restapi
        │               ├── dao
        │               │   └──
        │               ├── models
        │               │   └──
        │               └── resources
        │                   ├──
        │                   └──
        ├── resources
        │   └── META-INF
        │       └── persistence.xml
        └── webapp
            └── WEB-INF
                └── resources.xml

Now it's time to add some dependencies we need to create the application.
Open the project in your favorite IDE and add the following to the pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">






We added Java EE 7 api, H2 database and EclipseLink dependencies and TomEE maven runtime to our application.
In project directory run the following command to download the dependencies.

$ mvn install
TomEE Config
Open src/main/webapp/WEB-INF/resources.xml and add the following to configure DataSource.

<?xml version="1.0" encoding="UTF-8"?>
    <Resource id="jdbc/my_h2_db" type="javax.sql.DataSource">
        JdbcDriver = org.h2.Driver
        JdbcUrl = jdbc:h2:file:~/my_h2_db
        UserName = sa
        Password = sa
        jtaManaged = true

Now open persistence.xml and add the following to it.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
  <persistence-unit name="restapi_PU" transaction-type="JTA">
      <property name="eclipselink.ddl-generation" value="create-tables"/>
      <property name="eclipselink.ddl-generation.output-mode" value="database"/>

persistence.xml is the standard configuration file for JPA and it has to be included in the META-INF directory
The persistence.xml file defines what provider to be used, the name of the persistence unit, how classes should be mapped to database tables.
eclipselink.ddl-generation will create the database and tables

Open file and add the following

package com.kodnito.restapi.models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Table(name = "todos")
    @NamedQuery(name = "Todo.findAll", query = "SELECT t FROM Todo t")
public class Todo implements Serializable {

    private static final long serialVersionUID = 1L;

    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String task;
    private String description;

    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getTask() {
        return task;

    public void setTask(String task) {
        this.task = task;

    public String getDescription() {
        return description;

    public void setDescription(String description) {
        this.description = description;

    public String toString() {
        return "Todo{" + "id=" + id + ", task=" + task + ", description=" + description + '}';


@Entity annotation indicates that it is a JPA entity
@Table annotation is used to name the table in the database
@NamedQueries annotation is used to add multiple queries
@NamedQuery annotation defines query with a name
@Id annotation is used to define the primary key and the Id property is also annotated with @GeneratedValue to indicate that the Id should be generated automatically.

Business Logic
Open file and add the following

package com.kodnito.restapi.dao;

import com.kodnito.restapi.models.Todo;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class TodoDAO {

    @PersistenceContext(unitName = "restapi_PU")
    EntityManager em;

    public List getAll() {
        return em.createNamedQuery("Todo.findAll", Todo.class).getResultList();

    public Todo findById(Long id) {
        return em.find(Todo.class, id);

    public void update(Todo todo) {

    public void create(Todo todo) {

    public void delete(Todo todo) {
        if (!em.contains(todo)) {
            todo = em.merge(todo);


@PersistenceContext annotation injects the EntityManager to be used at runtime.
getAll() method retrieves all the todos from the database and return the entire list.
findById() method finds one Todo Object from the database with ID and returns it
update() method will update existing Todo Object in the database.
create() method will create Todo Object in the database
delete() method will find the Todo Object in the database and delete it.

Next step is to create the resource class.
Open and add the following.

package com.kodnito.resources;


public class ApplicationConfig extends Application {


@ApplicationPath annotation identifies the application path that will serve as the base for all our endpoints.
Now open and add the following to it

package com.kodnito.restapi.resources;

import com.kodnito.restapi.dao.TodoDAO;
import com.kodnito.restapi.models.Todo;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;

public class TodoResource {

    TodoDAO todoDAO;

    public Response getAll() {
        return Response.ok(todoDAO.getAll()).build();

    public Response getTodo(@PathParam("id") Long id) {
        Todo todo = todoDAO.findById(id);

        return Response.ok(todo).build();

    public Response update(@PathParam("id") Long id, Todo todo) {
        Todo updateTodo = todoDAO.findById(id);


        return Response.ok().build();

    public Response create(Todo todo) {
        return Response.ok().build();

    public Response delete(@PathParam("id") Long id) {
        Todo getTodo = todoDAO.findById(id);

        return Response.ok().build();


@RequestScoped annotation indicates that this class will be created once every request.
@Path annotation identifies the URI path to which the resource responds.
@Produces annotation will automatically convert the response to JSON format
@Consumes annotation will automatically convert the posted json string here into Todo object
We inject the TodoDAO with the @Inject annotation
@GET annotation maps /todos HTTP GET request to getAll() method, which will retrieve all the todos from the database and return the entire list.
Parameters are accessed with the @PathParam annotation.
@PUT annotation is for handling HTTP PUT request and it is meant to update an existing resource.
@POST annotation is for handling HTTP POST request and it is meant to create a new resource.
@DELETE annotation is for handling HTTP DELETE request.

It's time to test our new rest api.
Download Postman if you don't already have it.
Open your terminal and go the directory where you have your project and type the following command to compile the project and start the TomEE server.

$ mvn package tomee:run

Create TODO


Update TODO

Delete TODO

Share this: