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

Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications JavaAntoine Rey
 
Building beautiful apps with Google flutter
Building beautiful apps with Google flutterBuilding beautiful apps with Google flutter
Building beautiful apps with Google flutterAhmed Abu Eldahab
 
Kotlin Basics & Introduction to Jetpack Compose.pptx
Kotlin Basics & Introduction to Jetpack Compose.pptxKotlin Basics & Introduction to Jetpack Compose.pptx
Kotlin Basics & Introduction to Jetpack Compose.pptxtakshilkunadia
 
What is jenkins
What is jenkinsWhat is jenkins
What is jenkinslinuxdady
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsWebStackAcademy
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android ApplicationsRody Middelkoop
 
Présentation Flutter
Présentation FlutterPrésentation Flutter
Présentation FlutterAppstud
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask PresentationParag Mujumdar
 
Java servlets
Java servletsJava servlets
Java servletslopjuan
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework springAntoine Rey
 
Node js overview
Node js overviewNode js overview
Node js overviewEyal Vardi
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 

What's hot (20)

Spring boot
Spring bootSpring boot
Spring boot
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
 
Building beautiful apps with Google flutter
Building beautiful apps with Google flutterBuilding beautiful apps with Google flutter
Building beautiful apps with Google flutter
 
Kotlin Basics & Introduction to Jetpack Compose.pptx
Kotlin Basics & Introduction to Jetpack Compose.pptxKotlin Basics & Introduction to Jetpack Compose.pptx
Kotlin Basics & Introduction to Jetpack Compose.pptx
 
Light Tutorial Django
Light Tutorial DjangoLight Tutorial Django
Light Tutorial Django
 
What is jenkins
What is jenkinsWhat is jenkins
What is jenkins
 
La plateforme JEE
La plateforme JEELa plateforme JEE
La plateforme JEE
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Présentation Flutter
Présentation FlutterPrésentation Flutter
Présentation Flutter
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
[Open southcode] ios testing with appium
[Open southcode] ios testing with appium[Open southcode] ios testing with appium
[Open southcode] ios testing with appium
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
 
Java servlets
Java servletsJava servlets
Java servlets
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
 
Node js overview
Node js overviewNode js overview
Node js overview
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 

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...Knoldus Inc.
 
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
 
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

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...Jittipong Loespradit
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
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-learnAmarnathKambale
 
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
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
%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 Bahrainmasabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 

Recently uploaded (20)

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...
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
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
 
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
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
%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
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

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