SlideShare una empresa de Scribd logo
1 de 22
RESTful Java Play Framework
Simple JPA CRUD
Prerequisite
Play Framework 2.4.x
Download 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 Framework
Build basic API: GET, POST, PUT, DELETE
Build 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.Driver
db.default.url="jdbc:h2:mem:play"
db.default.jndiName=DefaultDS
jpa.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;
@Entity
public class Person {
@Id
@GeneratedValue
public long id;
public String name;
}
Create controller
Add the method addPerson() at controller
application.java
@Transactional
@BodyParser.Of(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 routes
GET /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":"inidevel
oper"}]
Get single record
Add url on routes
GET /person/:id controllers.Application.getPerson(id: Long)
Add controller Application.java
@Transactional
public 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"
}
PUT
Add url on routes
PUT /person/:id controllers.Application.updatePerson(id: Long)
Add controller Application.java
@Transactional
public 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 routes
DELETE /person/:id controllers.Application.deletePerson(id: Long)
Add controller Application.java
@Transactional
public 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 parameter
For example:
http://localhost:9000/searchperson?name=inideveloper
Add url on routes
GET /searchperson controllers.Application.searchPerson(name: String)
Add controller Application.java
@Transactional
public 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

Más contenido relacionado

La actualidad más candente

PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
Graham Dumpleton
 
A Brief Introduce to WSGI
A Brief Introduce to WSGIA Brief Introduce to WSGI
A Brief Introduce to WSGI
Mingli Yuan
 

La actualidad más candente (20)

Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Introduction to rest.li
Introduction to rest.liIntroduction to rest.li
Introduction to rest.li
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
A Brief Introduce to WSGI
A Brief Introduce to WSGIA Brief Introduce to WSGI
A Brief Introduce to WSGI
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
Google App Engine With Java And Groovy
Google App Engine With Java And GroovyGoogle App Engine With Java And Groovy
Google App Engine With Java And Groovy
 
Python WSGI introduction
Python WSGI introductionPython WSGI introduction
Python WSGI introduction
 
Pycon - Python for ethical hackers
Pycon - Python for ethical hackers Pycon - Python for ethical hackers
Pycon - Python for ethical hackers
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
The JavaFX Ecosystem
The JavaFX EcosystemThe JavaFX Ecosystem
The JavaFX Ecosystem
 
Serverless Java on Kubernetes
Serverless Java on KubernetesServerless Java on Kubernetes
Serverless Java on Kubernetes
 
Oracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web ServicesOracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web Services
 
Spring 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
 
An Introduction to Windows PowerShell
An Introduction to Windows PowerShellAn Introduction to Windows PowerShell
An Introduction to Windows PowerShell
 
Taking Apache Camel For A Ride
Taking Apache Camel For A RideTaking Apache Camel For A Ride
Taking Apache Camel For A Ride
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
 

Destacado (6)

Java Play RESTful ebean
Java Play RESTful ebeanJava Play RESTful ebean
Java Play RESTful ebean
 
Play2の裏側
Play2の裏側Play2の裏側
Play2の裏側
 
Microservices architecture
Microservices architectureMicroservices architecture
Microservices architecture
 
アドテク×Scala×パフォーマンスチューニング
アドテク×Scala×パフォーマンスチューニングアドテク×Scala×パフォーマンスチューニング
アドテク×Scala×パフォーマンスチューニング
 
Developing an Akka Edge1-3
Developing an Akka Edge1-3Developing an Akka Edge1-3
Developing an Akka Edge1-3
 
IES Triangle Principle
IES Triangle PrincipleIES Triangle Principle
IES Triangle Principle
 

Similar a Java Play Restful JPA

Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
Projeto-web-services-Spring-Boot-JPA.pdf
Projeto-web-services-Spring-Boot-JPA.pdfProjeto-web-services-Spring-Boot-JPA.pdf
Projeto-web-services-Spring-Boot-JPA.pdf
AdrianoSantos888423
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
PrinceGuru MS
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Alex Su
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 

Similar a Java Play Restful JPA (20)

Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platforms
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
Projeto-web-services-Spring-Boot-JPA.pdf
Projeto-web-services-Spring-Boot-JPA.pdfProjeto-web-services-Spring-Boot-JPA.pdf
Projeto-web-services-Spring-Boot-JPA.pdf
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security API
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
Specification-Driven Development of REST APIs by Alexander Zinchuk
Specification-Driven Development of REST APIs by Alexander Zinchuk   Specification-Driven Development of REST APIs by Alexander Zinchuk
Specification-Driven Development of REST APIs by Alexander Zinchuk
 
Core Php Component Presentation
Core Php Component PresentationCore Php Component Presentation
Core Php Component Presentation
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Spring data iii
Spring data iiiSpring data iii
Spring data iii
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 

Último

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 

Último (20)

tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 

Java Play Restful JPA

  • 1. RESTful Java Play Framework Simple JPA CRUD
  • 2. Prerequisite Play Framework 2.4.x Download here Setup the play framework (installing) JDK 1.8 (or later) IntelliJ CE
  • 3. Create New Project Through Command Line type: activator new
  • 4. Create New Project Open IntelliJ and import the new project
  • 5. Create New Project choose import project from external: SBT And next just let the default value, click finish
  • 6. Create New Project Here is the structure of Play framework
  • 7. The Objective Create RESTful with Java Play Framework Build basic API: GET, POST, PUT, DELETE Build parameterize API Use ORM (Object Relational Mapping) : JPA (Java Persistence Api)
  • 8. 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
  • 10. 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>
  • 11. 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()
  • 12. Create models Create models/Person.java package models; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Person { @Id @GeneratedValue public long id; public String name; }
  • 13. Create controller Add the method addPerson() at controller application.java @Transactional @BodyParser.Of(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(); }
  • 14. 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.
  • 15. Create Simple GET Add url on routes GET /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); }
  • 16. 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":"inidevel oper"}]
  • 17. Get single record Add url on routes GET /person/:id controllers.Application.getPerson(id: Long) Add controller Application.java @Transactional public Result getPerson(Long id){ Person person = JPA.em().find(Person.class, id); if (person==null){ return notFound("User not found"); } return ok(toJson(person)); }
  • 18. 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" }
  • 19. PUT Add url on routes PUT /person/:id controllers.Application.updatePerson(id: Long) Add controller Application.java @Transactional public 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(); }
  • 20. DELETE Add url on routes DELETE /person/:id controllers.Application.deletePerson(id: Long) Add controller Application.java @Transactional public 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(); }
  • 21. API with parameter For example: http://localhost:9000/searchperson?name=inideveloper Add url on routes GET /searchperson controllers.Application.searchPerson(name: String) Add controller Application.java @Transactional public 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"); } }