1. 程式人生 > >給JFinal新增 Sqlite 資料庫支援

給JFinal新增 Sqlite 資料庫支援

[轉自] http://my.oschina.net/u/237078/blog/69934

Sqlite 的單檔案便攜性、高效能在開發中方便性無與倫比,即使部署在中小型應用中也勝任有餘。

在JFinal中新增對 Sqlite 的支援 Step by Step:

3、使用資料庫管理工具建立一個數據庫,存放路徑為 Jfinal_app/WEB-INF/data.db ;建立必要的表,插入測試記錄,等等;

4、在 a_little_config.txt (或你自己的配置檔案) 中設定:

jdbcUrl = jdbc:sqlite:D:/webs/Jfinal_app/WEB-INF/data.db 
user = 
password = 
devMode = true

5、新建一個類 Sqlite3Dialect.java :(注:也可以等待JFinal 1.1.1版Jar將增加此類)

package com.jfinal.plugin.activerecord.dialect;
 
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.TableInfo;
 
/**
 * Sqlite3Dialect. Try to use Sqlite3 SQL dialect with ActiveRecordPlugin.
 * <p>
 * A clever person solves a problem. A wise person avoids it.
 */
public class Sqlite3SqlDialect implements IDialect {
     
    public String forTableInfoBuilderDoBuildTableInfo(String tableName) {
        return "select * from " + tableName + " where 1 = 2";
    }
     
    public void forModelSave(TableInfo tableInfo, Map<String, Object> attrs, StringBuilder sql, List<Object> paras) {
        sql.append("insert into ").append(tableInfo.getTableName()).append("(");
        StringBuilder temp = new StringBuilder(") values(");
        for (Entry<String, Object> e: attrs.entrySet()) {
            String colName = e.getKey();
            if (tableInfo.hasColumnLabel(colName)) {
                if (paras.size() > 0) {
                    sql.append(", ");
                    temp.append(", ");
                }
                sql.append(colName);
                temp.append("?");
                paras.add(e.getValue());
            }
        }
        sql.append(temp.toString()).append(")");
    }
     
    public String forModelDeleteById(TableInfo tInfo) {
        String pKey = tInfo.getPrimaryKey();
        StringBuilder sql = new StringBuilder(45);
        sql.append("delete from ");
        sql.append(tInfo.getTableName());
        sql.append(" where ").append(pKey).append(" = ?");
        return sql.toString();
    }
     
    public void forModelUpdate(TableInfo tableInfo, Map<String, Object> attrs, Set<String> modifyFlag, String pKey, Object id, StringBuilder sql, List<Object> paras) {
        sql.append("update ").append(tableInfo.getTableName()).append(" set ");
        for (Entry<String, Object> e : attrs.entrySet()) {
            String colName = e.getKey();
            if (!pKey.equalsIgnoreCase(colName) && modifyFlag.contains(colName) && tableInfo.hasColumnLabel(colName)) {
                if (paras.size() > 0)
                    sql.append(", ");
                sql.append(colName).append(" = ? ");
                paras.add(e.getValue());
            }
        }
        sql.append(" where ").append(pKey).append(" = ?");
        paras.add(id);
    }
     
    public String forModelFindById(TableInfo tInfo, String columns) {
        StringBuilder sql = new StringBuilder("select ");
        if (columns.trim().equals("*")) {
            sql.append(columns);
        }
        else {
            String[] columnsArray = columns.split(",");
            for (int i=0; i<columnsArray.length; i++) {
                if (i > 0)
                    sql.append(", ");
                sql.append(columnsArray[i].trim());
            }
        }
        sql.append(" from ");
        sql.append(tInfo.getTableName());
        sql.append(" where ").append(tInfo.getPrimaryKey()).append(" = ?");
        return sql.toString();
    }
     
    public String forDbFindById(String tableName, String primaryKey, String columns) {
        StringBuilder sql = new StringBuilder("select ");
        if (columns.trim().equals("*")) {
            sql.append(columns);
        }
        else {
            String[] columnsArray = columns.split(",");
            for (int i=0; i<columnsArray.length; i++) {
                if (i > 0)
                    sql.append(", ");
                sql.append(columnsArray[i].trim());
            }
        }
        sql.append(" from ");
        sql.append(tableName.trim());
        sql.append(" where ").append(primaryKey).append(" = ?");
        return sql.toString();
    }
     
    public String forDbDeleteById(String tableName, String primaryKey) {
        StringBuilder sql = new StringBuilder("delete from ");
        sql.append(tableName.trim());
        sql.append(" where ").append(primaryKey).append(" = ?");
        return sql.toString();
    }
     
    public void forDbSave(StringBuilder sql, List<Object> paras, String tableName, Record record) {
        sql.append("insert into ");
        sql.append(tableName.trim()).append("(");
        StringBuilder temp = new StringBuilder();
        temp.append(") values(");
         
        for (Entry<String, Object> e: record.getColumns().entrySet()) {
            if (paras.size() > 0) {
                sql.append(", ");
                temp.append(", ");
            }
            sql.append(e.getKey());
            temp.append("?");
            paras.add(e.getValue());
        }
        sql.append(temp.toString()).append(")");
    }
     
    public void forDbUpdate(String tableName, String primaryKey, Object id, Record record, StringBuilder sql, List<Object> paras) {
        sql.append("update ").append(tableName.trim()).append(" set ");
        for (Entry<String, Object> e: record.getColumns().entrySet()) {
            String colName = e.getKey();
            if (!primaryKey.equalsIgnoreCase(colName)) {
                if (paras.size() > 0) {
                    sql.append(", ");
                }
                sql.append(colName).append(" = ? ");
                paras.add(e.getValue());
            }
        }
        sql.append(" where ").append(primaryKey).append(" = ?");
        paras.add(id);
    }
     
    public void forPaginate(StringBuilder sql, int pageNumber, int pageSize, String select, String sqlExceptSelect) {
        int offset = pageSize * (pageNumber - 1);
        sql.append(select).append(" ");
        sql.append(sqlExceptSelect);
        sql.append(" limit ").append(offset).append(", ").append(pageSize); // limit can use one or two '?' to pass paras
    }
}

6、在DemoConfig.java (或你自己的 Config 類)中:
import com.jfinal.plugin.activerecord.dialect.Sqlite3Dialect;

public void configPlugin(Plugins me) {
    // 配置C3p0資料庫連線池外掛
    C3p0Plugin c3p0Plugin = new C3p0Plugin(getProperty("jdbcUrl"), getProperty("user"), getProperty("password"));
            c3p0Plugin.setDriverClass("org.sqlite.JDBC"); //指定驅動程式
            me.add(c3p0Plugin); 
    // 配置ActiveRecord外掛
    ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
    me.add(arp);
            arp.setDialect(new Sqlite3Dialect());  //指定 Dialect
            arp.addMapping("blog", Blog.class); // 對映blog 表到 Blog模型
}

7、至此大功告成!啟動,伺服器,在瀏覽器中檢視效果吧!