[英]Simple CRUD tutorial about Play Framework and MySQL using Ebean?
我是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
万岁!
列出行动
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的人都有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.