Search in sources :

Example 1 with JdbcExpert

use of org.nutz.dao.jdbc.JdbcExpert in project nutz by nutzam.

the class ExtDaoInvocationHandler method dataDict.

/** 根据Pojo生成数据字典,zdoc格式 */
public static StringBuilder dataDict(Dao dao, String... packages) {
    StringBuilder sb = new StringBuilder();
    List<Class<?>> ks = new ArrayList<Class<?>>();
    for (String packageName : packages) {
        ks.addAll(Scans.me().scanPackage(packageName));
    }
    Iterator<Class<?>> it = ks.iterator();
    while (it.hasNext()) {
        Class<?> klass = it.next();
        if (klass.getAnnotation(Table.class) == null)
            it.remove();
    }
    // log.infof("Found %d table class", ks.size());
    JdbcExpert exp = dao.getJdbcExpert();
    Entity<?> entity = null;
    String line = "-------------------------------------------------------------------\n";
    sb.append("#title:数据字典\n");
    sb.append("#author:wendal\n");
    sb.append("#index:0,1\n").append(line);
    for (Class<?> klass : ks) {
        sb.append(line);
        entity = dao.getEntity(klass);
        sb.append("表名 ").append(entity.getTableName()).append("\n\n");
        if (!Strings.isBlank(entity.getTableComment()))
            sb.append("表注释: ").append(entity.getTableComment());
        sb.append("\t").append("Java类名 ").append(klass.getName()).append("\n\n");
        sb.append("\t||序号||列名||数据类型||主键||非空||默认值||java属性名||java类型||注释||\n");
        int index = 1;
        for (MappingField field : entity.getMappingFields()) {
            String dataType = exp.evalFieldType(field);
            sb.append("\t||").append(index++).append("||").append(field.getColumnName()).append("||").append(dataType).append("||").append(field.isPk()).append("||").append(field.isNotNull()).append("||").append(field.getDefaultValue(null) == null ? " " : field.getDefaultValue(null)).append("||").append(field.getName()).append("||").append(field.getTypeClass().getName()).append("||").append(field.getColumnComment() == null ? " " : field.getColumnComment()).append("||\n");
        }
    }
    return sb;
}
Also used : Table(org.nutz.dao.entity.annotation.Table) JdbcExpert(org.nutz.dao.jdbc.JdbcExpert) ArrayList(java.util.ArrayList) MappingField(org.nutz.dao.entity.MappingField)

Example 2 with JdbcExpert

use of org.nutz.dao.jdbc.JdbcExpert 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 3 with JdbcExpert

use of org.nutz.dao.jdbc.JdbcExpert in project nutz by nutzam.

the class NutDao method setExpert.

// ---------------------------------------------------------------
// 专属于NutDao的一些帮助方法
public void setExpert(Object obj) throws Exception {
    if (obj == null)
        throw new NullPointerException("expert MUST NOT NULL!!");
    if (obj instanceof JdbcExpert) {
        this.expert = (JdbcExpert) obj;
    } else {
        String name = obj.toString();
        this.expert = Jdbcs.getExpert(name, "");
        if (this.expert == null) {
            if (name.contains(".")) {
                this.expert = (JdbcExpert) Lang.loadClass(name).newInstance();
            } else {
                throw new DaoException("not such expert=" + obj);
            }
        }
    }
    DataSource ds = this.dataSource;
    // 如果数据源比expert先设置,那么需要重新设置一次
    if (ds != null) {
        this.dataSource = null;
        setDataSource(ds);
    }
}
Also used : JdbcExpert(org.nutz.dao.jdbc.JdbcExpert) DaoException(org.nutz.dao.DaoException) DataSource(javax.sql.DataSource)

Example 4 with JdbcExpert

use of org.nutz.dao.jdbc.JdbcExpert in project nutz by nutzam.

the class ExtDaoInvocationHandler method checkTableColumn.

/**
     * 检查分表中是否有字段变化 提示
     *
     * @param dao
     *            Dao实例
     * @param tableName
     *            动态表名上下文
     * @param clsType
     *            映射Pojo
     */
public static void checkTableColumn(Dao dao, Object tableName, final Class<?> clsType) {
    final NutDao d = (NutDao) dao;
    final JdbcExpert expert = d.getJdbcExpert();
    ext(d, tableName).run(new ConnCallback() {

        public void invoke(Connection conn) throws Exception {
            Entity<?> en = d.getEntity(clsType);
            expert.setupEntityField(conn, en);
        }
    });
}
Also used : Entity(org.nutz.dao.entity.Entity) NutDao(org.nutz.dao.impl.NutDao) JdbcExpert(org.nutz.dao.jdbc.JdbcExpert) ConnCallback(org.nutz.dao.ConnCallback) Connection(java.sql.Connection) DaoException(org.nutz.dao.DaoException) SQLException(java.sql.SQLException)

Example 5 with JdbcExpert

use of org.nutz.dao.jdbc.JdbcExpert in project nutz by nutzam.

the class SimpleDaoTest method test_migration.

@Test
public void test_migration() {
    dao.execute(Sqls.create("drop table t_pet"));
    Entity<Pet> en = dao.getEntity(Pet.class);
    NutDao dao = (NutDao) this.dao;
    JdbcExpert expert = dao.getJdbcExpert();
    MappingField mf = en.getField("age");
    String str = "create table t_pet (" + mf.getColumnName() + " " + expert.evalFieldType(mf) + "," + mf.getColumnName() + "_2" + " " + expert.evalFieldType(mf) + ")";
    dao.execute(Sqls.create(str));
    Daos.migration(dao, Pet.class, !dao.meta().isSQLite(), !dao.meta().isSQLite());
}
Also used : NutDao(org.nutz.dao.impl.NutDao) JdbcExpert(org.nutz.dao.jdbc.JdbcExpert) MappingField(org.nutz.dao.entity.MappingField) Issue1163Pet(org.nutz.dao.test.meta.issue1163.Issue1163Pet) Pet(org.nutz.dao.test.meta.Pet) Test(org.junit.Test)

Aggregations

JdbcExpert (org.nutz.dao.jdbc.JdbcExpert)5 DaoException (org.nutz.dao.DaoException)3 MappingField (org.nutz.dao.entity.MappingField)3 Connection (java.sql.Connection)2 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 ConnCallback (org.nutz.dao.ConnCallback)2 NutDao (org.nutz.dao.impl.NutDao)2 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 ResultSetMetaData (java.sql.ResultSetMetaData)1 Statement (java.sql.Statement)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 DataSource (javax.sql.DataSource)1 Test (org.junit.Test)1 Entity (org.nutz.dao.entity.Entity)1 Table (org.nutz.dao.entity.annotation.Table)1 Sql (org.nutz.dao.sql.Sql)1 Pet (org.nutz.dao.test.meta.Pet)1