日期:2014-05-16  浏览次数:20604 次

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