SlideShare a Scribd company logo
1 of 24
RESTful Java Play Framework
Simple ebean 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) : Ebean
Configuration
plugin.sbt at project/ folder, uncomment or add
this:
addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "1.0.0”)
Configuration
build.sbt (root)
name := """Java-Play-RESTful-JPA"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean)
scalaVersion := "2.11.6"
libraryDependencies ++= Seq(
javaJdbc,
cache,
javaWs
)
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
Still on conf/application.conf, add:
ebean.default="models.*”
This is as ORM related object model mapping
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 com.avaje.ebean.Model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Person extends Model{
@Id
public Long id;
public String name;
public static Finder<Integer, Person> find
= new Finder<Integer, Person>(Integer.class, Person.class);
}
Create controller
Add the method addPerson() at controller
application.java
@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");
}
person.save();
return ok();
}
Let’s try
First create run configuration: Choose SBT Task and chose for the Task
is run.
Execute Run.
Because of the first
time server start, it
need trigger script
evolution execute first
by open the base url
on the browser and
apply the script.
Let’s try
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
public Result listPerson(){
List<Person> persons = new Model.Finder(String.class,
Person.class).all();
return ok(toJson(persons));
}
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":33,"name":"Faren"}]
Get single record
Add url on routes
GET /person/:id controllers.Application.getPerson(id: Int)
Add controller Application.java
public Result getPerson(int id){
Person person = Person.find.byId(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: Int)
Add controller Application.java
@BodyParser.Of(BodyParser.Json.class)
public Result updatePerson(int id){
Person person = Person.find.byId(id);
if (person == null){
return notFound("User not found");
}
JsonNode json = request().body().asJson();
Person personToBe = Json.fromJson(json, Person.class);
person = personToBe;
person.update();
return ok();
}
DELETE
Add url on routes
DELETE /person/:id controllers.Application.deletePerson(id: Int)
Add controller Application.java
public Result deletePerson(int id){
Person person = Person.find.byId(id);
if (person == null){
return notFound("User not found");
}
person.delete();
return ok();
}
API with parameter
For example:
http://localhost:9000/searchperson?name=Faren
Add url on routes
GET /searchperson controllers.Application.searchPerson(name: String)
Add controller Application.java
public Result searchPerson(String name){
List<Person> persons = Person.find.where()
.like("name", "%"+name+"%")
.findList();
if (persons == null){
return notFound("User not found!");
}
return ok(toJson(persons));
}
Full Source Code:
https://github.com/faren/java-play-ebean

More Related Content

What's hot

Git Introduction
Git IntroductionGit Introduction
Git IntroductionGareth Hall
 
Kotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a treeKotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a treeKai Koenig
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.jsPagepro
 
Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware TutorialSimplilearn
 
Play Framework: The Basics
Play Framework: The BasicsPlay Framework: The Basics
Play Framework: The BasicsPhilip Langer
 
Puppeteer can automate that! - Frontmania
Puppeteer can automate that! - FrontmaniaPuppeteer can automate that! - Frontmania
Puppeteer can automate that! - FrontmaniaÖnder Ceylan
 
Puppeteer - A web scraping & UI Testing Tool
Puppeteer - A web scraping & UI Testing ToolPuppeteer - A web scraping & UI Testing Tool
Puppeteer - A web scraping & UI Testing ToolMiki Lombardi
 
UDA-Plugin UDA. Guia de desarrollo
UDA-Plugin UDA. Guia de desarrolloUDA-Plugin UDA. Guia de desarrollo
UDA-Plugin UDA. Guia de desarrolloAnder Martinez
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Visual Engineering
 
Java agents for fun and (not so much) profit
Java agents for fun and (not so much) profitJava agents for fun and (not so much) profit
Java agents for fun and (not so much) profitRobert Munteanu
 
Estilos css en code igniter « _ walter
Estilos css en code igniter «  _ walterEstilos css en code igniter «  _ walter
Estilos css en code igniter « _ walterSander Sanchez Reyes
 
Token Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreToken Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreStormpath
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
Concevoir, développer et sécuriser des micro-services avec Spring Boot
Concevoir, développer et sécuriser des micro-services avec Spring BootConcevoir, développer et sécuriser des micro-services avec Spring Boot
Concevoir, développer et sécuriser des micro-services avec Spring BootDNG Consulting
 

What's hot (20)

SQLite - Overview
SQLite - OverviewSQLite - Overview
SQLite - Overview
 
Git Introduction
Git IntroductionGit Introduction
Git Introduction
 
Support de cours technologie et application m.youssfi
Support de cours technologie et application m.youssfiSupport de cours technologie et application m.youssfi
Support de cours technologie et application m.youssfi
 
Tutoriel J2EE
Tutoriel J2EETutoriel J2EE
Tutoriel J2EE
 
Kotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a treeKotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a tree
 
Struts2
Struts2Struts2
Struts2
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware Tutorial
 
Play Framework: The Basics
Play Framework: The BasicsPlay Framework: The Basics
Play Framework: The Basics
 
Puppeteer can automate that! - Frontmania
Puppeteer can automate that! - FrontmaniaPuppeteer can automate that! - Frontmania
Puppeteer can automate that! - Frontmania
 
Puppeteer - A web scraping & UI Testing Tool
Puppeteer - A web scraping & UI Testing ToolPuppeteer - A web scraping & UI Testing Tool
Puppeteer - A web scraping & UI Testing Tool
 
UDA-Plugin UDA. Guia de desarrollo
UDA-Plugin UDA. Guia de desarrolloUDA-Plugin UDA. Guia de desarrollo
UDA-Plugin UDA. Guia de desarrollo
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Java agents for fun and (not so much) profit
Java agents for fun and (not so much) profitJava agents for fun and (not so much) profit
Java agents for fun and (not so much) profit
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Estilos css en code igniter « _ walter
Estilos css en code igniter «  _ walterEstilos css en code igniter «  _ walter
Estilos css en code igniter « _ walter
 
Token Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreToken Authentication in ASP.NET Core
Token Authentication in ASP.NET Core
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Concevoir, développer et sécuriser des micro-services avec Spring Boot
Concevoir, développer et sécuriser des micro-services avec Spring BootConcevoir, développer et sécuriser des micro-services avec Spring Boot
Concevoir, développer et sécuriser des micro-services avec Spring Boot
 

Similar to Java Play RESTful ebean

Java Play Restful JPA
Java Play Restful JPAJava Play Restful JPA
Java Play Restful JPAFaren faren
 
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
 
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
 
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...Neelkanth Sachdeva
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Knoldus Inc.
 
Rally - Benchmarking_as_a_service - Openstack meetup
Rally - Benchmarking_as_a_service - Openstack meetupRally - Benchmarking_as_a_service - Openstack meetup
Rally - Benchmarking_as_a_service - Openstack meetupAnanth Padmanabhan
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript Glenn Stovall
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidenceJohn Congdon
 
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...DynamicInfraDays
 
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
 
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
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Tino Isnich
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesLindsay Holmwood
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
 
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
 

Similar to Java Play RESTful ebean (20)

Java Play Restful JPA
Java Play Restful JPAJava Play Restful JPA
Java Play Restful JPA
 
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
 
Serverless Java on Kubernetes
Serverless Java on KubernetesServerless Java on Kubernetes
Serverless Java on Kubernetes
 
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)
 
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
 
Rally - Benchmarking_as_a_service - Openstack meetup
Rally - Benchmarking_as_a_service - Openstack meetupRally - Benchmarking_as_a_service - Openstack meetup
Rally - Benchmarking_as_a_service - Openstack meetup
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
 
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
 
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
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
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
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 

Recently uploaded

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 

Java Play RESTful ebean

  • 1. RESTful Java Play Framework Simple ebean 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) : Ebean
  • 8. Configuration plugin.sbt at project/ folder, uncomment or add this: addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "1.0.0”)
  • 9. Configuration build.sbt (root) name := """Java-Play-RESTful-JPA""" version := "1.0-SNAPSHOT" lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean) scalaVersion := "2.11.6" libraryDependencies ++= Seq( javaJdbc, cache, javaWs ) routesGenerator := InjectedRoutesGenerator
  • 11. Configuration Still on conf/application.conf, add: ebean.default="models.*” This is as ORM related object model mapping
  • 12. 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()
  • 13. Create models Create models/Person.java package models; import com.avaje.ebean.Model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Person extends Model{ @Id public Long id; public String name; public static Finder<Integer, Person> find = new Finder<Integer, Person>(Integer.class, Person.class); }
  • 14. Create controller Add the method addPerson() at controller application.java @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"); } person.save(); return ok(); }
  • 15. Let’s try First create run configuration: Choose SBT Task and chose for the Task is run. Execute Run. Because of the first time server start, it need trigger script evolution execute first by open the base url on the browser and apply the script.
  • 16. Let’s try 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.
  • 17. Create Simple GET Add url on routes GET /person controllers.Application.listPerson() Add controller Application.java public Result listPerson(){ List<Person> persons = new Model.Finder(String.class, Person.class).all(); return ok(toJson(persons)); }
  • 18. 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":33,"name":"Faren"}]
  • 19. Get single record Add url on routes GET /person/:id controllers.Application.getPerson(id: Int) Add controller Application.java public Result getPerson(int id){ Person person = Person.find.byId(id); if (person == null){ return notFound("User not found!"); } return ok(toJson(person)); }
  • 20. 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" }
  • 21. PUT Add url on routes PUT /person/:id controllers.Application.updatePerson(id: Int) Add controller Application.java @BodyParser.Of(BodyParser.Json.class) public Result updatePerson(int id){ Person person = Person.find.byId(id); if (person == null){ return notFound("User not found"); } JsonNode json = request().body().asJson(); Person personToBe = Json.fromJson(json, Person.class); person = personToBe; person.update(); return ok(); }
  • 22. DELETE Add url on routes DELETE /person/:id controllers.Application.deletePerson(id: Int) Add controller Application.java public Result deletePerson(int id){ Person person = Person.find.byId(id); if (person == null){ return notFound("User not found"); } person.delete(); return ok(); }
  • 23. API with parameter For example: http://localhost:9000/searchperson?name=Faren Add url on routes GET /searchperson controllers.Application.searchPerson(name: String) Add controller Application.java public Result searchPerson(String name){ List<Person> persons = Person.find.where() .like("name", "%"+name+"%") .findList(); if (persons == null){ return notFound("User not found!"); } return ok(toJson(persons)); }