play 1.x框架的配置与使用(二)

本示例使用的play为1.2.7。

这里示范一下持久化和读取数据库的操作。

1.  配置JPA和数据库,JPA使用Hibernate,数据库为MySql

在/conf/application.conf 里编辑:

# JPA Configuration (Hibernate)
jpa.dialect=org.hibernate.dialect.MySQLDialect
# 在控制台里面可以看到生成的SQL语句
jpa.debugSQL=true

# MySql Configuration
# If you need a full JDBC configuration use the following :
 db.url=jdbc:mysql://127.0.0.1:3306/exam?useUnicode=true&characterEncoding=utf8
 db.driver=com.mysql.jdbc.Driver
 db.user=root
 db.pass=

 2.  建立Model类

package models;


import play.db.jpa.Model;

import javax.persistence.Entity;
import javax.persistence.Table;

/**
 * 体检套餐产品类
 * Created by jiangzhiqiang on 15/4/29.
 */
@Entity
@Table(name="product")
public class Product extends Model{

    //public Integer id;
    public String name;
    public Integer price;
    public Integer hospitalId;
    public String scope;


}

 3.  在Controller中添加数据库操作代码

编辑/Controller/Application.java

public class Application extends Controller {

    public static void index() {
        List<Product> productList = Product.findAll();
        for(Product product:productList){
            System.out.println("id:"+product.id);
            System.out.println("name:"+product.name);
        }
        render();
    }

}

 4.  测试

在Brower中访问 http://localhost:9000

终端显示:

16:21:32,600 DEBUG ~ select product0_.id as id4_, product0_.hospitalId as hospitalId4_, product0_.name as name4_, product0_.price as price4_, product0_.scope as scope4_ from product product0_
id:1
name:老年人标准体检套餐
id:2
name:老年人超值体检套餐
id:3
name:老年人全面体检套餐
id:4
name:老年人标准体检套餐
id:5
name:中年人标准体检套餐
id:6
name:老年人金秋健康套餐
id:7
name:老年标准体检套餐A

 测试成功

5.  结论:

Play!Framework使用简单,开发和调试高效,不失为一个基于Java语言的优秀框架。

猜你喜欢

转载自geeksun.iteye.com/blog/2207154