A simple CRUD tutorial on Play Framework and MySQL using Ebean?

I am new to Play Framework. I started to study it, and still I like it. I started learning Play Java.

I have my controller and model installed as follows:

Controller:

package controllers; import play.mvc.Controller; import play.mvc.Result; //Import Product model import models.Product; public class Products extends Controller{ /** * List all Products */ public static Result list(){ Object allProducts = Product.findAll(); return ok((Content) allProducts); //return all products } } 

Model:

 package models; import java.util.List; import play.db.*; import play.api.db.DB; import com.avaje.ebean.Ebean; import com.avaje.ebean.Query; public class Product { public int id; public String name; public String description; public Product(){ } public Product(int id, String name, String description){ this.id = id; this.name = name; this.description = description; } public static String findAll(){ //Using ebean and MySql, fech the product table //and return all products } } 

To enable the use of MySql, I already edited the /conf/application.conf file as follows:

 db.default.driver=com.mysql.jdbc.Driver db.default.url="jdbc:mysql://localhost/play_db?characterEncoding=UTF-8" db.default.user=user db.default.password=pass ebean.default="models.*" 

I have a play_db database with one table shown below:

enter image description here

My problem is how to get all the products in the product model using ebean and MySQL. Can someone please point me to a simple crud tutorial that uses java games in conjunction with ebean and MySql? Thanks

Is anyone

Note By the way, I am using Play v.2.3.5 for Java

+7
source share
1 answer

Hooray !!!

List action

 public static Result list(){ List<Product> products = Product.findAll(); return ok(play.libs.Json.toJson(products)); } 

findAll method in product model

 public static List<Product> findAll(){ return Product.find.orderBy("id").findList(); } 

Finally, I have to enable evolution in /conf/application.conf, uncommenting the following line

 # evolutionplugin=disabled 

Add @Entity before public class Product extends model {

End Code:

 package models; import java.util.List; import javax.persistence.Entity; import play.db.*; import play.db.ebean.Model; import play.api.db.DB; import com.avaje.ebean.Ebean; import com.avaje.ebean.Query; @Entity public class Product extends Model{ public int id; public String name; public String description; public static Model.Finder<String, Product> find = new Model.Finder<String, Product>(String.class, Product.class); public Product(){ } public Product(int id, String name, String description){ this.id = id; this.name = name; this.description = description; } public static List<Product> findAll(){ return Product.find.orderBy("id").findList(); } } 

I hope this helps anyone who is also new to Play Java

+8
source share

All Articles