Learn Java for Web Development

(Tina Meador) #1

380 CHAPTER 8: Play with Java and Scala


This will create an Ebean server connected to the default data source, managing all entities found in
the models package.


Now it’s time to transform your Book class to a valid Ebean entity. You can do this by making the Book
class extend the play.db.ebean.Model superclass to have access to Play’s built-in Ebean helper, as
illustrated in Listing 8-15.


Listing 8-15. Transforming the Book Class to a Valid Ebean Entity



  1. package models;



  2. import java.util.*;

  3. import play.db.ebean.*;

  4. import play.data.validation.Constraints.*;



  5. import javax.persistence.*;



  6. @Entity

  7. public class Book extends Model {

  8. @Id

  9. public Long id;

  10. @Required

  11. public String label;



  12. public static Finder<Long,Book> find = new Finder(

  13. Long.class, Book.class

  14. );





  15. public static List all() {

  16. return find.all();

  17. }



  18. public static void create(Book book) {

  19. book.save();

  20. }

  21. public static void update(Long id, Book book) {

  22. book.update(id);

  23. }



  24. public static void delete(Long id) {

  25. find.ref(id).delete();

  26. }





  27. }


   Line 13: Line 13 adds the persistence annotation.
 Lines 16 to 18: These lines create a finder helper called find to initiate queries.
 Lines 21 to 34: These lines implement the CRUD operations. For instance, when you
call the create() action, Ebean translates the save() method call into one or more
SQL INSERT statements that store a new record in a database table using SQL.
Free download pdf