Java Play Restful JPA

22
RESTful Java Play Framework Simple JPA CRUD

Transcript of Java Play Restful JPA

RESTful Java Play Framework

Simple JPA CRUD

Prerequisite

Play Framework 2.4.xDownload here

Setup the play framework (installing)JDK 1.8 (or later)IntelliJ CE

Create New Project

Through Command Line type: activator new

Create New Project

Open IntelliJ and import the new project

Create New Project

choose import project from external: SBT

And next just let the default value, click

finish

Create New Project

Here is the structure of Play

framework

The Objective

Create RESTful with Java Play FrameworkBuild basic API: GET, POST, PUT, DELETEBuild parameterize API

Use ORM (Object Relational Mapping) : JPA (Java Persistence Api)

Configuration

build.sbt (root)name := """Java-Play-RESTful-JPA"""

version := "1.0-SNAPSHOT"

lazy val root = (project in file(".")).enablePlugins(PlayJava)

scalaVersion := "2.11.6"

libraryDependencies ++= Seq( javaJdbc, cache, javaWs, javaJpa, "org.hibernate" % "hibernate-entitymanager" % "3.6.9.Final”)

routesGenerator := InjectedRoutesGenerator

Configuration

conf/application.conf, add:db.default.driver=org.h2.Driverdb.default.url="jdbc:h2:mem:play"db.default.jndiName=DefaultDSjpa.default=defaultPersistenceUnit

For simple purpose (development), we use mem as database on memory.

Configuration

Create persistence.xml at conf/META-INF

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">

<persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <non-jta-data-source>DefaultDS</non-jta-data-source> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>

<property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit>

</persistence>

Create Simple POST

At conf/routes, we add url for API access.

POST /person controllers.Application.addperson()

The method is POST, the access to this API is {baseurl}/person. For this example, we use json format for body.The process is on controllers/Application.java method addperson()

Create models

Create models/Person.java

package models;

import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;

@Entitypublic class Person {

@Id @GeneratedValue public long id;

public String name;}

Create controller

Add the method addPerson() at controller application.java@[email protected](BodyParser.Json.class)public Result addPerson(){ JsonNode json = request().body().asJson();

Person person = Json.fromJson(json, Person.class);

if (person.toString().equals("")){ return badRequest("Missing parameter"); }

JPA.em().persist(person); return ok();}

Let’s try

First create run configuration: Choose SBT Task and chose for the Task is run.Execute Run.Let curl from command line:curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{ "name":"Faren"}' 'http://localhost:9000/person'

It will store one object Person.

Create Simple GET

Add url on routesGET /person controllers.Application.listPerson()

Add controller Application.java@Transactional(readOnly = true)public Result listPerson(){ CriteriaBuilder cb = JPA.em().getCriteriaBuilder(); CriteriaQuery<Person> cq = cb.createQuery(Person.class);

Root<Person> root = cq.from(Person.class); CriteriaQuery<Person> all = cq.select(root);

TypedQuery<Person> allQuery = JPA.em().createQuery(all);

JsonNode jsonNode = toJson(allQuery.getResultList()); return ok(jsonNode);}

Let’s try

No need to Rerun the server. Just curl the GET method from command line.curl -X GET -H "Cache-Control: no-cache" 'http://localhost:9000/person’

The Output:[{"id":1,"name":"Faren"},{"id":2,"name":"Dromdev"},{"id":3,"name":"inideveloper"}]

Get single record

Add url on routesGET /person/:id controllers.Application.getPerson(id: Long)

Add controller Application.java@Transactionalpublic Result getPerson(Long id){ Person person = JPA.em().find(Person.class, id);

if (person==null){ return notFound("User not found"); }

return ok(toJson(person));}

Let’s try

Run curl on command line:curl -X GET -H "Cache-Control: no-cache" 'http://localhost:9000/person/1’

The Output:{ "id": 1, "name": "Faren"}

PUTAdd url on routesPUT /person/:id controllers.Application.updatePerson(id: Long)

Add controller Application.java@Transactionalpublic Result updatePerson(Long id){ Person person = JPA.em().find(Person.class, id);

if (person==null){ return notFound("User not found"); }

JsonNode json= request().body().asJson();

Person personToBe = Json.fromJson(json, Person.class);

person.name = personToBe.name;

return ok();}

DELETE

Add url on routesDELETE /person/:id controllers.Application.deletePerson(id: Long)

Add controller Application.java@Transactionalpublic Result deletePerson(Long id){ Person person = JPA.em().find(Person.class, id);

if (person==null){ return notFound("User not found"); }

JPA.em().remove(person);

return ok();}

API with parameterFor example:http://localhost:9000/searchperson?name=inideveloper

Add url on routesGET /searchperson controllers.Application.searchPerson(name: String)

Add controller Application.java@Transactionalpublic Result searchPerson(String name){

TypedQuery<Person> query = JPA.em().createQuery ("select p from Person p where p.name = :name", Person.class) .setParameter("name", name);

try { Person person = query.getSingleResult(); return ok(toJson(person));

}catch (NoResultException e){ return notFound("User not found"); }

}

Full Source Code:

https://github.com/faren/java-play-jpa