Learn Java for Web Development

(Tina Meador) #1
CHAPTER 8: Play with Java and Scala 379

Listing 8-14. Implementation of the newBook( ) Action



  1. public static Result newBook() {

  2. Form filledForm = bookForm.bindFromRequest();

  3. if(filledForm.hasErrors()) {

  4. return badRequest(

  5. views.html.index.render(Book.all(), filledForm)

  6. );

  7. } else {

  8. Book.create(filledForm.get());

  9. return redirect(routes.Application.books());

  10. }

  11. }


   Line 2: We use bindFromRequest to create a new form filled with the request data.
 Lines 3 to 7: If there are any errors in the form, we redisplay it (here we use 400
“Bad Request” instead of 200 “OK”).
 Lines 7 to 10: If there are no errors, we create the book and then redirect to the
books list.

Accessing the Database

Play 2 supports an object-relational mapping (ORM), Ebean, out of the box to fill the gap
between the domain model and the relational database, as illustrated in Figure 8 -2 4. The other
popular options that offer ORM for Java are Hibernate and the Java Persistence API, which is
standardized by Oracle.


Figure 8-24. Using Ebean to query the database


Like any other ORM, Ebean aims to facilitate the usage of a model when dealing with relational
databases by implementing finders based on the model’s properties. You will use H2, a lightweight
DBMS that comes bundled with Play 2. Play’s configuration contains default settings for using H2
and Ebean, but they’re commented out. So, open the file conf/application.conf in your application’s
directory, and find and uncomment the following lines to enable the database in your application:


db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"


You will use Ebean to query the database. So, you’ll have to enable it in the application.conf file as well:


ebean.default="models.*"

Free download pdf