我是Play Framework的新手。我已经开始学习它,到目前为止我很享受它。 我已经开始学习Play Java。
我的控制器和模型设置如下:
控制器:
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
}
}
型号:
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
}
}
为了能够使用MySql,我已经编辑了/conf/application.conf,如下所示:
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.*"
我有一个play_db数据库,其中一个表如下所示:
我的问题是如何使用ebean和MySQL获取Product模型中的所有产品。 有人可以指点一个简单的crud教程,它将play java与ebean和MySql结合使用?感谢
任何?
注意 顺便说一下,我正在使用Play v.2.3.5 for Java
答案 0 :(得分:8)
万岁!!!
列出操作
public static Result list(){
List<Product> products = Product.findAll();
return ok(play.libs.Json.toJson(products));
}
在产品型号中查找所有方法
public static List<Product> findAll(){
return Product.find.orderBy("id").findList();
}
最后,我必须通过取消注释以下行来启用/conf/application.conf中的evolution
# evolutionplugin=disabled
在公共类产品扩展模型{
之前添加 @Entity最终代码:
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();
}
}
我希望这对任何刚接触Play Java的人都有帮助