Java Play RESTful ebean
Click here to load reader
-
Upload
faren-faren -
Category
Software
-
view
703 -
download
1
Transcript of Java Play RESTful ebean
RESTful Java Play Framework
Simple ebean CRUD
Prerequisite
Play Framework 2.4.xDownload here
Setup the play framework (installing)JDK 1.8 (or later)IntelliJ CE
Create New Project
Through Command Line type: activator new
Create New Project
Open IntelliJ and import the new project
Create New Project
choose import project from external: SBT
And next just let the default value, click
finish
Create New Project
Here is the structure of Play
framework
The Objective
Create RESTful with Java Play FrameworkBuild basic API: GET, POST, PUT, DELETEBuild parameterize API
Use ORM (Object Relational Mapping) : 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.Driverdb.default.url="jdbc:h2:mem:play"db.default.jndiName=DefaultDSjpa.default=defaultPersistenceUnit
For simple purpose (development), we use mem as database on memory.
Configuration
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;
@Entitypublic 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 [email protected](BodyParser.Json.class)public Result addPerson(){ JsonNode json = request().body().asJson();
Person person = Json.fromJson(json, Person.class);
if (person.toString().equals("")){ return badRequest("Missing parameter"); }
person.save(); return ok();}
Let’s tryFirst 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 routesGET /person controllers.Application.listPerson()
Add controller Application.javapublic 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.javapublic 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"}
PUTAdd url on routesPUT /person/:id controllers.Application.updatePerson(id: Int)
Add controller [email protected](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 parameterFor example:http://localhost:9000/searchperson?name=Faren
Add url on routesGET /searchperson controllers.Application.searchPerson(name: String)
Add controller Application.javapublic 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