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
- package models;
- import java.util.*;
- import play.db.ebean.*;
- import play.data.validation.Constraints.*;
- import javax.persistence.*;
- @Entity
- public class Book extends Model {
- @Id
- public Long id;
- @Required
- public String label;
- public static Finder<Long,Book> find = new Finder(
- Long.class, Book.class
- );
- public static List
all() { - return find.all();
- }
- public static void create(Book book) {
- book.save();
- }
- public static void update(Long id, Book book) {
- book.update(id);
- }
- public static void delete(Long id) {
- find.ref(id).delete();
- }
- }
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.