Search in sources :

Example 6 with MappingField

use of org.nutz.dao.entity.MappingField in project nutz by nutzam.

the class ExtDaoInvocationHandler method filterFields.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static boolean filterFields(Object obj, FieldMatcher matcher, Dao dao, Callback2<MappingField, Object> callback) {
    if (obj == null)
        return false;
    obj = Lang.first(obj);
    if (obj == null) {
        return false;
    }
    if (obj.getClass() == Class.class) {
        throw Lang.impossible();
    }
    if (obj instanceof String || obj instanceof Number || obj instanceof Boolean) {
        throw Lang.impossible();
    }
    Entity en = dao.getEntity(obj.getClass());
    if (en == null) {
        throw Lang.impossible();
    }
    List<MappingField> mfs = new ArrayList<MappingField>(en.getMappingFields());
    if (matcher != null) {
        Iterator<MappingField> it = mfs.iterator();
        while (it.hasNext()) {
            MappingField mf = it.next();
            if (!matcher.match(mf.getName()))
                it.remove();
        }
    }
    boolean flag = false;
    for (MappingField mf : mfs) {
        if (matcher == null) {
            Object val = mf.getValue(obj);
            callback.invoke(mf, val);
            flag = true;
            continue;
        }
        if (matcher.isIgnoreId() && mf.isId())
            continue;
        if (matcher.isIgnoreName() && mf.isName())
            continue;
        if (matcher.isIgnorePk() && mf.isCompositePk())
            continue;
        Object val = mf.getValue(obj);
        if (val == null) {
            if (matcher.isIgnoreNull())
                continue;
        } else {
            if (matcher.isIgnoreZero() && val instanceof Number && ((Number) val).doubleValue() == 0.0) {
                continue;
            }
            if (matcher.isIgnoreDate() && val instanceof Date) {
                continue;
            }
            if (matcher.isIgnoreBlankStr() && val instanceof String) {
            }
        }
        callback.invoke(mf, val);
        flag = true;
    }
    return flag;
}
Also used : Entity(org.nutz.dao.entity.Entity) ArrayList(java.util.ArrayList) MappingField(org.nutz.dao.entity.MappingField) Date(java.util.Date)

Example 7 with MappingField

use of org.nutz.dao.entity.MappingField in project nutz by nutzam.

the class ExtDaoInvocationHandler method migration.

/**
     * 为数据表自动增减字段
     *
     * @param dao
     *            Dao实例
     * @param klass
     *            映射Pojo
     * @param add
     *            是否允许添加字段
     * @param del
     *            是否允许删除字段
     * @param checkIndex
     *            是否检查索引
     * @param tableName
     *            动态表名上下文
     */
public static void migration(Dao dao, final Class<?> klass, final boolean add, final boolean del, final boolean checkIndex, final Object tableName) {
    final JdbcExpert expert = dao.getJdbcExpert();
    if (tableName != null && Strings.isNotBlank(tableName.toString())) {
        dao = ext(dao, tableName);
    }
    final Entity<?> en = dao.getEntity(klass);
    if (!dao.exists(klass))
        return;
    final List<Sql> sqls = new ArrayList<Sql>();
    final Set<String> _indexs = new HashSet<String>();
    dao.run(new ConnCallback() {

        public void invoke(Connection conn) throws Exception {
            expert.setupEntityField(conn, en);
            Statement stat = null;
            ResultSet rs = null;
            ResultSetMetaData meta = null;
            try {
                // 获取数据库元信息
                stat = conn.createStatement();
                rs = stat.executeQuery("select * from " + en.getTableName() + " where 1 != 1");
                meta = rs.getMetaData();
                Set<String> columnNames = new HashSet<String>();
                int columnCount = meta.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    columnNames.add(meta.getColumnName(i).toLowerCase());
                }
                for (MappingField mf : en.getMappingFields()) {
                    if (mf.isReadonly())
                        continue;
                    String colName = mf.getColumnName();
                    if (columnNames.contains(colName.toLowerCase())) {
                        columnNames.remove(colName.toLowerCase());
                        continue;
                    }
                    if (add) {
                        log.infof("add column[%s] to table[%s]", mf.getColumnName(), en.getTableName());
                        sqls.add(expert.createAddColumnSql(en, mf));
                    }
                }
                if (del) {
                    for (String colName : columnNames) {
                        log.infof("del column[%s] from table[%s]", colName, en.getTableName());
                        Sql sql = Sqls.create("ALTER table $table DROP column $name");
                        sql.vars().set("table", en.getTableName());
                        sql.vars().set("name", colName);
                        sqls.add(sql);
                    }
                }
                // show index from mytable;
                if (checkIndex)
                    _indexs.addAll(expert.getIndexNames(en, conn));
            } catch (SQLException e) {
                if (log.isDebugEnabled())
                    log.debugf("migration Table '%s' fail!", en.getTableName(), e);
            } finally // Close ResultSet and Statement
            {
                Daos.safeClose(stat, rs);
            }
        }
    });
    // 创建索引
    UpdateIndexSql indexSqls = createIndexs(dao, en, _indexs, tableName);
    if (checkIndex) {
        // 因为已删除的字段的索引是没办法删除的 所以要先处理索引 再处理字段
        Sql[] delIndexSqls = indexSqls.getSqlsDel();
        if (!Lang.isEmptyArray(delIndexSqls)) {
            dao.execute(delIndexSqls);
        }
    }
    for (Sql sql : sqls) {
        dao.execute(sql);
    }
    if (checkIndex) {
        Sql[] addIndexSqls = indexSqls.getSqlsAdd();
        if (!Lang.isEmptyArray(addIndexSqls)) {
            dao.execute(addIndexSqls);
        }
    }
    // 创建关联表
    dao.getJdbcExpert().createRelation(dao, en);
}
Also used : ResultSet(java.sql.ResultSet) Set(java.util.Set) HashSet(java.util.HashSet) JdbcExpert(org.nutz.dao.jdbc.JdbcExpert) ConnCallback(org.nutz.dao.ConnCallback) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) MappingField(org.nutz.dao.entity.MappingField) DaoException(org.nutz.dao.DaoException) SQLException(java.sql.SQLException) Sql(org.nutz.dao.sql.Sql) ResultSetMetaData(java.sql.ResultSetMetaData) ResultSet(java.sql.ResultSet) HashSet(java.util.HashSet)

Example 8 with MappingField

use of org.nutz.dao.entity.MappingField in project nutz by nutzam.

the class ExtDaoInvocationHandler method createIndexs.

private static UpdateIndexSql createIndexs(Dao dao, Entity<?> en, Set<String> indexsHis, Object t) {
    UpdateIndexSql uis = new UpdateIndexSql();
    List<Sql> sqls = new ArrayList<Sql>();
    List<String> delIndexs = new ArrayList<String>();
    List<EntityIndex> indexs = en.getIndexes();
    for (EntityIndex index : indexs) {
        sqls.add(dao.getJdbcExpert().createIndexSql(en, index));
    }
    if (!Lang.isEmpty(sqls)) {
        uis.setSqlsAdd(sqls.toArray(new Sql[0]));
    }
    Iterator<String> iterator = indexsHis.iterator();
    List<Sql> delSqls = new ArrayList<Sql>();
    while (iterator.hasNext()) {
        String index = iterator.next();
        if (delIndexs.contains(index) || Lang.equals("PRIMARY", index)) {
            continue;
        }
        MappingField mf = en.getColumn(index);
        if (mf != null) {
            if (mf.isName())
                continue;
        }
        delSqls.add(Sqls.createf("ALTER TABLE %s DROP INDEX %s", getTableName(dao, en, t), index));
    }
    if (!Lang.isEmpty(delSqls)) {
        uis.setSqlsDel(Lang.collection2array(delSqls));
    }
    return uis;
}
Also used : ArrayList(java.util.ArrayList) EntityIndex(org.nutz.dao.entity.EntityIndex) MappingField(org.nutz.dao.entity.MappingField) Sql(org.nutz.dao.sql.Sql)

Example 9 with MappingField

use of org.nutz.dao.entity.MappingField in project nutz by nutzam.

the class Cnd method from.

/**
     * 根据一个对象生成Cnd条件, FieldMatcher详细控制.<p/>
     * <code>assertEquals(" WHERE name='wendal' AND age=0", Cnd.from(dao, pet, FieldMatcher.make("age|name", null, true).setIgnoreDate(true)).toString());</code>
     * @param dao Dao实例
     * @param obj 基对象,不可以是Class,字符串,数值和Boolean
     * @param matcher 过滤字段属性, 可配置哪些字段可用/不可用/是否忽略空值/是否忽略0值/是否忽略java.util.Date类及其子类的对象/是否忽略@Id所标注的主键属性/是否忽略 \@Name 所标注的主键属性/是否忽略 \@Pk 所引用的复合主键 
     * @return Cnd条件
     */
public static Cnd from(Dao dao, Object obj, FieldMatcher matcher) {
    final SqlExpressionGroup exps = new SqlExpressionGroup();
    boolean re = Daos.filterFields(obj, matcher, dao, new Callback2<MappingField, Object>() {

        public void invoke(MappingField mf, Object val) {
            exps.and(mf.getName(), "=", val);
        }
    });
    if (re)
        return Cnd.where(exps);
    return null;
}
Also used : SqlExpressionGroup(org.nutz.dao.util.cri.SqlExpressionGroup) MappingField(org.nutz.dao.entity.MappingField)

Example 10 with MappingField

use of org.nutz.dao.entity.MappingField in project nutz by nutzam.

the class QueryEntityFieldsPItem method joinSql.

public void joinSql(Entity<?> en, StringBuilder sb) {
    FieldMatcher fm = getFieldMatcher();
    if (null == fm) {
        sb.append("* ");
    } else {
        List<MappingField> efs = _en(en).getMappingFields();
        int old = sb.length();
        for (MappingField ef : efs) {
            if (fm.match(ef.getName()))
                sb.append(ef.getColumnNameInSql()).append(',');
        }
        if (sb.length() == old)
            throw Lang.makeThrow("No columns be queryed: '%s'", _en(en));
        sb.setCharAt(sb.length() - 1, ' ');
    }
}
Also used : MappingField(org.nutz.dao.entity.MappingField) FieldMatcher(org.nutz.dao.FieldMatcher)

Aggregations

MappingField (org.nutz.dao.entity.MappingField)33 Sql (org.nutz.dao.sql.Sql)14 ArrayList (java.util.ArrayList)12 SQLException (java.sql.SQLException)5 PreparedStatement (java.sql.PreparedStatement)4 DaoException (org.nutz.dao.DaoException)4 Connection (java.sql.Connection)3 Chain (org.nutz.dao.Chain)3 ConnCallback (org.nutz.dao.ConnCallback)3 JdbcExpert (org.nutz.dao.jdbc.JdbcExpert)3 ResultSet (java.sql.ResultSet)2 ResultSetMetaData (java.sql.ResultSetMetaData)2 Statement (java.sql.Statement)2 HashSet (java.util.HashSet)2 Test (org.junit.Test)2 ValueAdaptor (org.nutz.dao.jdbc.ValueAdaptor)2 Date (java.util.Date)1 Set (java.util.Set)1 FieldFilter (org.nutz.dao.FieldFilter)1 FieldMatcher (org.nutz.dao.FieldMatcher)1