I am new to Play Framework. I have started learning it and so far I am enjoying it. I have started to learn Play Java.
I have my controller and model set up as follow:
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 have already edited the /conf/application.conf as follow:
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 as follow:
My problem is how to fetch all the products in the Product model using ebean and MySQL. Can someone please point me to a simple crud tutorial which uses play java in combination with ebean and MySql? Thanks
Anyone?
NOTE By the way, I am using Play v.2.3.5 for Java
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();
}
Lastly, I have to enable evolution in /conf/application.conf by uncommenting the following line
# evolutionplugin=disabled
Add @Entity just before public class Product extends Model{
Final 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 will help anyone who is also new to Play Java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With