`
sillycat
  • 浏览: 2567432 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

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


分享到:
评论

相关推荐

    Play Framework

    5. 使用 Play 框架开发 Java 应用 5.1 HTTP编程 5.1.1 什么是 Action? 5.1.2 什么是 Result ? 5.1.3 什么是 Controller? 5.1.4 Session 和 Flash 5.2 异步 HTTP 编程 5.3 对 WebSocket 的支持 5.4 如何...

    Play framework框架

    Play Framework框架是一种基于Java的软件框架,旨在提高开发效率和提供REST式的架构风格。该框架可以让开发者继续使用他们喜欢的开发环境或繻库,不需要切换到另一种语言、IDE或者其他繻库。 一、Play Framework...

    playframework javaweb

    playframework javaweb playframework javaweb

    playframework中文教程.zip

    Play Framework 是一个开源的Web应用框架,主要针对Java和Scala开发者设计,它的核心理念是简化开发流程,提高开发效率,并且特别强调了RESTful架构风格。这个“playframework中文教程.zip”压缩包很可能是为了帮助...

    Play Framework Cookbook.pdf

    - **框架简介**:Play Framework 是一个开源的 Web 开发框架,基于 Java 和 Scala 编程语言。它采用轻量级、非阻塞的服务端架构,特别适合开发高性能、可扩展的应用程序。Play Framework 通过其独特的设计理念简化了...

    play framework api,play! framework api,play api

    Play Framework 是一个开源的Web应用框架,用于构建现代、高性能的Java和Scala应用程序。它采用模型-视图-控制器(MVC)架构模式,并且强调简洁的代码和开发的即时反馈。Play Framework API 是开发者使用该框架进行...

    Play Framework Cookbook

    - **定义与背景**:Play Framework 是一款基于 Java 和 Scala 的高性能、轻量级 Web 开发框架。它采用 RESTful 架构设计,支持热重载功能,能够显著提高开发效率。本书(《Play Framework Cookbook》)提供了超过 60...

    PlayFramework框架验证.pdf

    PlayFramework是一个高性能的Java和Scala框架,它支持Web应用的快速开发,并且主要面向RESTful应用程序。在PlayFramework中,为了确保数据的准确性和合法性,通常会在数据保存到数据库之前,对HTTP请求中的参数进行...

    playFramework1.2.3

    5. **内置数据库支持**:Play Framework集成了JPA(Java Persistence API),并默认支持H2内存数据库,使得开发者可以快速进行原型开发。同时,它也支持其他关系型数据库,如MySQL、PostgreSQL等,通过简单的配置...

    play,play framework资料大全

    Play Framework 是一个基于Java的开源Web应用框架,它遵循MVC(模型-视图-控制器)架构模式,致力于简化Web应用程序的开发过程。这个资料大全包含了许多关于Play Framework的重要资源,帮助开发者深入理解和高效使用...

    Play Framework应用程序框架 v2.7.9.zip

    Play Framework是一款基于Java和Scala的开源Web应用框架,它遵循模型-视图-控制器(MVC)架构模式,旨在提供高效、简洁且可测试的开发环境。标题中的"v2.7.9"指的是该框架的特定版本,通常每个新版本会包含性能优化...

    Java Web框架Play Framework v2.1.0.zip

    Play Framework是一个full-stack(全栈的)Java Web应用框架,包括一个简单的无状态MVC模型,具有Hibernate的对象持续,一个基于Groovy的模板引擎,以及建立一个现代Web应用所需的所有东西。   Play Framework的...

    playframework 框架学习之路 1

    Play Framework 是一个基于Java和Scala的开源Web应用框架,它遵循模型-视图-控制器(MVC)架构模式。在“Playframework框架学习之路 1”中,我们可能要探讨这个框架的基础概念、安装过程以及如何创建一个简单的应用...

    Play framework 2.0 -第一个应用程序

    Play Framework 2.0 是一个开源的Web应用框架,它基于Scala和Java语言,遵循“模式-动作”(Action)架构,提供了一种轻量级、敏捷开发的方式。本篇文章将引导你通过创建一个简单的待办事项(Todo List)应用来了解...

    Play Framework2本教程

    Play Framework2是一个强大的Java和Scala应用开发框架,它以其简洁的API、快速的开发周期以及对Web标准的紧密集成而闻名。本教程旨在为初学者和有经验的开发者提供全面的指导,帮助他们掌握Play Framework2的核心...

    Mastering Play Framework for Scala

    Mastering Play Framework for Scala

    playframework增删改查

    Play Framework 是一个基于Java和Scala的开源Web应用框架,它遵循模型-视图-控制器(MVC)架构模式。在本教程中,我们将探讨如何利用Play Framework与MySQL数据库交互,实现基本的CRUD(创建、读取、更新、删除)...

    playframework框架项目部署文档

    Play Framework是一个强大的、基于Java和Scala的开源Web应用程序框架,它采用模型-视图-控制器(MVC)架构模式,以简洁的API和直观的开发体验受到开发者喜爱。本篇文章将详述如何在Windows环境下安装配置Play环境...

    Play framework 2.0入门教程(三)的源代码,Play留言板

    Play Framework 2.0 是一个基于Java和Scala的开源Web应用程序框架,以其“写后即运行”的特性而闻名。这个入门教程的第三部分是关于如何使用Play Framework构建一个简单的留言板应用。在这里,我们将深入探讨Play ...

Global site tag (gtag.js) - Google Analytics