Java Play RESTful ebean

24

Click here to load reader

Transcript of Java Play RESTful ebean

Page 1: Java Play RESTful ebean

RESTful Java Play Framework

Simple ebean CRUD

Page 2: Java Play RESTful ebean

Prerequisite

Play Framework 2.4.xDownload here

Setup the play framework (installing)JDK 1.8 (or later)IntelliJ CE

Page 3: Java Play RESTful ebean

Create New Project

Through Command Line type: activator new

Page 4: Java Play RESTful ebean

Create New Project

Open IntelliJ and import the new project

Page 5: Java Play RESTful ebean

Create New Project

choose import project from external: SBT

And next just let the default value, click

finish

Page 6: Java Play RESTful ebean

Create New Project

Here is the structure of Play

framework

Page 7: Java Play RESTful ebean

The Objective

Create RESTful with Java Play FrameworkBuild basic API: GET, POST, PUT, DELETEBuild parameterize API

Use ORM (Object Relational Mapping) : Ebean

Page 8: Java Play RESTful ebean

Configuration

plugin.sbt at project/ folder, uncomment or add this:addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "1.0.0”)

Page 9: Java Play RESTful ebean

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

Page 10: Java Play RESTful ebean

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.

Page 11: Java Play RESTful ebean

Configuration

Still on conf/application.conf, add:ebean.default="models.*”

This is as ORM related object model mapping

Page 12: Java Play RESTful ebean

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()

Page 13: Java Play RESTful ebean

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

Page 14: Java Play RESTful ebean

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

Page 15: Java Play RESTful ebean

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.

Page 16: Java Play RESTful ebean

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.

Page 17: Java Play RESTful ebean

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

Page 18: Java Play RESTful ebean

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"}]

Page 19: Java Play RESTful ebean

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

}

Page 20: Java Play RESTful ebean

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

Page 21: Java Play RESTful ebean

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

Page 22: Java Play RESTful ebean

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

Page 23: Java Play RESTful ebean

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

}

Page 24: Java Play RESTful ebean

Full Source Code:

https://github.com/faren/java-play-ebean