Play Framework 2.x includes an object-relational mapping tool called Ebean for Java-based Play applications. To be able to use Ebean, ensure that Ebean and a suitable MySQL driver are declared as project dependencies in foo_java/build.sbt
.
For this recipe, we will be utilizing Ebean with database evolutions. Play Framework 2.x gives developers a way to manage database migrations. Database migrations are useful for tracking schema changes during the course of application development. Database evolutions are enabled by default but can be disabled in conf/application.conf
with the following settings:
evolutionplugin=disabled
Evolution scripts are stored in the conf/evolutions/default/
directory. For more information regarding database evolutions, please refer to Play's online documentation at
https://www.playframework.com/documentation/2.3.x/Evolutions.
You need to perform the following steps to utilize Ebean:
Add the Ebean dependency in
build.sbt
:libraryDependencies ++= Seq( javaJdbc, javaEbean, "mysql" % "mysql-connector-java" % "5.1.28" )
Ensure that Ebean and MySQL are configured properly in
conf/application.conf
:db.default.driver=com.mysql.jdbc.Driver db.default.url="jdbc:mysql://<YOUR_MYSQL_HOST>/<YOUR_DB>" db.default.user=<YOUR_USER> db.default.password=<YOUR_PASSWORD> ebean.default="models.*"
For the next recipes, we need to create our product table in our MySQL database. Create our first database evolution file
1.sql
inconf/evolutions/default
and add the following SQL statements:# --- !Ups CREATE TABLE Products ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(100) NOT NULL, PRIMARY KEY (id) ); # --- !Downs DROP TABLE Products;
The next step is to create the Ebean model for our entity
Product
:package models; import java.util.*; import javax.persistence.*; import play.db.ebean.*; import play.data.format.*; import play.data.validation.*; @Entity @Table(name = "Products") public class Product extends Model { @Id public Long id; @Column @Constraints.Required public String name; public static Finder<Long, Product> find = new Finder<Long, Product>( Long.class, Product.class ); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
The following displays various database-oriented operations using Ebean.
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
The following code snippet will create a new record:
Product product = new Product(); product.name = "Apple iPhone"; product.save();