Playframework(5)Java Project and SQL Database

Playframework(5)Java Project and SQL Database

8. Accessing an SQL Database
Configuring JDBC connection pools
conf/application.conf

# Default database configuration
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"

#Orders database
db.orders.driver=org.h2.Driver
db.orders.url="jdbc:h2:mem:order"

#customers database
db.customers.driver=org.h2.Driver
db.customers.url="jdbc:h2:mem:customers"

Accessing the JDBC database: Database ds = DB.getDatasource();

Obtaining a JDBC connection    Connection connection = DB.getConnection();

Exposing the datasource through JNDI
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:men:play"
db.default.jndiName=DefaultDS

Using Ebean ORM
http://www.avaje.org/

conf/application.conf:
ebean.default="models.*"

ebean.orders="models.Order, models.OrderItem"
ebean.customer="models.Customer, models.Address"

Using the play.dv.ebean.Model Superclass
@Entity
public class Task extends Model{
     @Id
     @Constraints.Min(10)
     public Long id;

     @constraints.Required
     public String name;

     public boolean done;
    
     @Format.DateTime(pattern="dd/MM/yyyy")
     public Data dueDate = new Date();

     public static Finder<Long,Task> find = new Finder<Long, Task>(
          Long.class, Task.class
     );
}

Allmost like hibernate

Transactional actions
We need to enable the helper for that on Ebean.

Intergrating with JPA
Exposing the datasource through JNDI

Adding a JPA implementation to my project
"org.hibernate" % "hibernate-entitymanager" % "3.6.9.Final"

Creating a persistence unit
conf/META-INF/persistence.xml

Annotating JPA actions with @Transactional

Using the play.db.jpa.JPA helper
public static Company findById(Long id){
     return JPA.em().find(Company.class, id);
}

9 The Play Cache API
The default cache API uses EHCache.    play.cache.Cache
Cache.set("item.key", frontPageNews);

News news = Cache.get("item.key");

Remove the cache, Cache.set("item.key", null, 0)       Cache.remove("item.key")

Caching HTTP Responses
@Cached("homePage")
public static Result index(){
     return ok("Hello world");
}

10. Calling WebService
play.libs.WS provides a way to make asynchronous HTTP calls.

We will use promise then.

11. Integration with Akka

12. Internationalization

13. Application Global Settings
The Global Object
We need to define a global object in the root package
import play.*;
public class Global extends GlobalSettings{
}

Intercepting application start-up and shutdown
public class Global extends GlobalSettings{
     public void onStart(Application app){
          Logger.info("Application has started");
     }

     public void onStop(Application app){
          Logger.info("Application shutdown...");
     }
}

Providing an application error page
When an exception occurs in my application, the onError operation will be called.

public class Global extends GlobalSettings{
     public Result onError(Throwable t){
          return internalSeverError(
               views.html.errorPage(t)
          );
     }
}

Handling action not found
If the framework doesn't find an action method for a request, the onHandlerNotFound operation will be called:
public class Global extends GlobalSettings{
     public Result onHandlerNotFound(String uri){
          return notFound(
               views.html.pageNotFound(uri)
          );
     }
}

The onBadRequest operation will be called if a route was found, but it was not possible to bind the request parameters.
public class Global extends GlobalSettings{
     public Result onBadRequest(String uri, String error){
          return badRequest("Don't try to hack the URI!");
     }
}

Intercepting Requests
One important aspect of the GlobalSettings class is that it provides a way to intercept requests and execute business logic before a request is dispatched to an action.

public class Global extends GlobalSettings{
     public Action onRequest(Request request, Method actionMethod){
          System.out.println("before each request…" + request.toString());
          return super.onRequest(request, actionMethod);
     }
}

14. Testing Your Application
Using JUnit and Running a fake application

fakeApplication(inMemoryDatabase())

Writing functional tests
Testing a template
@Test
public void renderTemplate(){
     Content html = views.html.index.render("Coco");
     assertThat(contentType(html)).isEqualTo("text/html");
     assertThat(ContentAsString(html)).contains("Coco");
}

Testing your controllers
@Test
public void callIndex(){
     Result result = callAction(
          controllers.routes.ref.Application.index("Kiko");
     );
     assertThat(status(result)).isEqualTo(OK);
     assertThat(contentType(result)).isEqualTo("text/html");
     assertThat(charset(result)).isEqualTo("utf-8");
     assertThat(contentAsString(result)).contains("Hello Kiki");
}

Testing the router
Instead of calling the Action, we can let the Router do it.
@Test
public void badRoute(){
     Result result = routeAndCall(fakeRequest(GET, "/xx/Kiki"));
     assertThat(result).isNull();
}

Starting a real HTTP server
@Test
public void testInServer(){
     running(testServe(3333), new Callback0(){
          assertThat(
               WS.url("http://localhot:3333").get().get().status
          ).isEqualTo(OK);
     });
}

Testing from within a web browser
Selenium WebDriver
@Test
public void runInBrowser(){
     running(testServer(3333), HTMLUNIT, new Callback<TestBrowser>(){
          public void invoke(TestBrowser browser){
               browser.goTo("http://localhost:3333");
               assertThat(browser.$("#title").getTexts().get(0)).isEqualTo("Hello Guest");
               browser.$("a").click();

               assertThat(browser.url()).isEqualTo("http://localhost:3333/Coco");
               assertThat(browser.$("#title", 0).getText()).isEqualTo("Hello Coco");
          }
     })
}

References:
http://www.playframework.org/documentation/2.0.4/JavaHome
http://www.playframework.org/documentation/2.0.4/JavaDatabase


你可能感兴趣的:(playframework)