SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to rest.li
Introduction to rest.liIntroduction to rest.li
Introduction to rest.liJoe Betz
 
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 2Graham Dumpleton
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90minsLarry Cai
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
A Brief Introduce to WSGI
A Brief Introduce to WSGIA Brief Introduce to WSGI
A Brief Introduce to WSGIMingli Yuan
 
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 jsfakedarren
 
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 GroovyKen Kousen
 
Python WSGI introduction
Python WSGI introductionPython WSGI introduction
Python WSGI introductionAgeeleshwar K
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 
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 ServicesKim Berg Hansen
 
An Introduction to Windows PowerShell
An Introduction to Windows PowerShellAn Introduction to Windows PowerShell
An Introduction to Windows PowerShellDale Lane
 
Taking Apache Camel For A Ride
Taking Apache Camel For A RideTaking Apache Camel For A Ride
Taking Apache Camel For A RideBruce Snyder
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Kenji Tanaka
 

Was ist angesagt? (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クライアントのテスト -
 

Andere mochten auch

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

Andere mochten auch (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
 

Ähnlich wie Java Play Restful JPA

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 platformsAyush Sharma
 
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 OracleRaimonds Simanovskis
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
 
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.pdfAdrianoSantos888423
 
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 APIcaswenson
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
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 gradleThierry Wasylczenko
 
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)Yevgeniy Brikman
 
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 OdessaJS Conf
 
Core Php Component Presentation
Core Php Component PresentationCore Php Component Presentation
Core Php Component PresentationJohn Coonen
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8PrinceGuru MS
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfacesmaccman
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
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.xYiguang Hu
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 
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 frameworkBen Lin
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 

Ähnlich wie 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
 

Kürzlich hochgeladen

VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 

Kürzlich hochgeladen (20)

VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 

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"); } }