Search in sources :

Example 6 with ConnCallback

use of org.nutz.dao.ConnCallback in project nutz by nutzam.

the class InsertTest method test_fastInsert_rollback_jdbc.

/**
     * Github Issue #131, 这个证明了 JDBC 驱动支持事务
     */
@Test
public void test_fastInsert_rollback_jdbc() {
    dao.create(Pet.class, true);
    try {
        Trans.exec(new Molecule<Object>() {

            public void run() {
                dao.run(new ConnCallback() {

                    public void invoke(Connection conn) throws Exception {
                        PreparedStatement ps = conn.prepareStatement("INSERT INTO t_pet(name) VALUES(?)");
                        for (int i = 0; i < 100; i++) {
                            ps.setString(1, "XXXXX" + i);
                            ps.addBatch();
                        }
                        ps.execute();
                    }
                });
                throw new RuntimeException();
            }
        });
    } catch (Throwable e) {
    }
    assertEquals(0, dao.count(Pet.class));
}
Also used : ConnCallback(org.nutz.dao.ConnCallback) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Pet(org.nutz.dao.test.meta.Pet) Test(org.junit.Test)

Example 7 with ConnCallback

use of org.nutz.dao.ConnCallback in project nutz by nutzam.

the class EntityHolder method makeEntity.

@SuppressWarnings({ "rawtypes", "unchecked" })
public <T extends Map<String, ?>> Entity<T> makeEntity(String tableName, T map) {
    final NutEntity<T> en = new NutEntity(map.getClass());
    en.setTableName(tableName);
    en.setViewName(tableName);
    boolean check = false;
    for (Entry<String, ?> entry : map.entrySet()) {
        String key = entry.getKey();
        // 是实体补充描述吗?
        if (key.startsWith("#")) {
            en.getMetas().put(key.substring(1), entry.getValue().toString());
            continue;
        } else // 以 "." 开头的字段,不是实体字段
        if (key.startsWith(".")) {
            continue;
        }
        // 是实体字段
        Object value = entry.getValue();
        Mirror<?> mirror = Mirror.me(value);
        NutMappingField ef = new NutMappingField(en);
        if (key.startsWith("+")) {
            ef.setAsAutoIncreasement();
            if (mirror != null && mirror.isIntLike())
                ef.setAsId();
            key = key.substring(1);
        }
        if (key.startsWith("!")) {
            ef.setAsNotNull();
            key = key.substring(1);
        }
        if (key.startsWith("*")) {
            key = key.substring(1);
            if (mirror != null && mirror.isIntLike())
                ef.setAsId();
            else
                ef.setAsName();
        }
        ef.setName(key);
        ef.setType(null == value ? Object.class : value.getClass());
        ef.setColumnName(key);
        // 猜测一下数据库类型
        Jdbcs.guessEntityFieldColumnType(ef);
        ef.setAdaptor(expert.getAdaptor(ef));
        if (mirror != null)
            ef.setType(mirror.getType());
        // 这里比较纠结,回设的时候应该用什么呢?
        ef.setInjecting(new InjectToMap(key));
        ef.setEjecting(new EjectFromMap(entry.getKey()));
        if (ef.isAutoIncreasement() && ef.isId() && expert.isSupportAutoIncrement() && !expert.isSupportGeneratedKeys()) {
            en.addAfterInsertMacro(expert.fetchPojoId(en, ef));
        }
        en.addMappingField(ef);
        if (mirror != null && !check)
            check = mirror.isEnum();
    }
    en.checkCompositeFields(null);
    // 最后在数据库中验证一下实体各个字段
    if (check)
        connCallback.invoke(new ConnCallback() {

            public void invoke(Connection conn) throws Exception {
                expert.setupEntityField(conn, en);
            }
        });
    // 搞定返回
    return en;
}
Also used : ConnCallback(org.nutz.dao.ConnCallback) NutEntity(org.nutz.dao.impl.entity.NutEntity) Connection(java.sql.Connection) NutMappingField(org.nutz.dao.impl.entity.field.NutMappingField) InjectToMap(org.nutz.lang.inject.InjectToMap) EjectFromMap(org.nutz.lang.eject.EjectFromMap)

Example 8 with ConnCallback

use of org.nutz.dao.ConnCallback in project nutz by nutzam.

the class NutDao method exists.

public boolean exists(final String tableName) {
    final boolean[] ee = { false };
    this.run(new ConnCallback() {

        public void invoke(Connection conn) {
            Statement stat = null;
            ResultSet rs = null;
            try {
                stat = conn.createStatement();
                // 增加不等式,减少sql执行时间
                String sql = "SELECT COUNT(1) FROM " + tableName + " where 1!=1";
                rs = stat.executeQuery(sql);
                if (rs.next())
                    ee[0] = true;
            } catch (SQLException e) {
            } finally {
                Daos.safeClose(stat, rs);
            }
        }
    });
    return ee[0];
}
Also used : ConnCallback(org.nutz.dao.ConnCallback) SQLException(java.sql.SQLException) DaoStatement(org.nutz.dao.sql.DaoStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet)

Example 9 with ConnCallback

use of org.nutz.dao.ConnCallback 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 10 with ConnCallback

use of org.nutz.dao.ConnCallback in project nutz by nutzam.

the class ExtDaoInvocationHandler method updateBySpecialChain.

/**
     * 执行一个特殊的Chain(事实上普通Chain也能执行,但不建议使用)
     *
     * @see org.nutz.dao.Chain#addSpecial(String, Object)
     */
@SuppressWarnings({ "rawtypes" })
public static int updateBySpecialChain(Dao dao, Entity en, String tableName, Chain chain, Condition cnd) {
    if (en != null)
        tableName = en.getTableName();
    if (tableName == null)
        throw Lang.makeThrow(DaoException.class, "tableName and en is NULL !!");
    final StringBuilder sql = new StringBuilder("UPDATE ").append(tableName).append(" SET ");
    Chain head = chain.head();
    final List<Object> values = new ArrayList<Object>();
    final List<ValueAdaptor> adaptors = new ArrayList<ValueAdaptor>();
    while (head != null) {
        MappingField mf = null;
        if (en != null)
            mf = en.getField(head.name());
        String colName = head.name();
        if (mf != null)
            colName = mf.getColumnNameInSql();
        sql.append(colName).append("=");
        if (head.special()) {
            if (head.value() != null && head.value() instanceof String) {
                String str = (String) head.value();
                if (str.length() > 0) {
                    switch(str.charAt(0)) {
                        case '+':
                        case '-':
                        case '*':
                        case '/':
                        case '%':
                        case '&':
                        case '^':
                        case '|':
                            sql.append(colName);
                            break;
                    }
                }
            }
            sql.append(head.value());
        } else {
            sql.append("?");
            values.add(head.value());
            ValueAdaptor adaptor = Jdbcs.getAdaptorBy(head.value());
            if (mf != null && mf.getAdaptor() != null)
                adaptor = mf.getAdaptor();
            adaptors.add(adaptor);
        }
        sql.append(" ");
        head = head.next();
        if (head != null)
            sql.append(", ");
    }
    if (cnd != null)
        sql.append(" ").append(cnd.toSql(en));
    if (log.isDebugEnabled())
        log.debug(sql);
    final int[] ints = new int[1];
    dao.run(new ConnCallback() {

        public void invoke(Connection conn) throws Exception {
            PreparedStatement ps = conn.prepareStatement(sql.toString());
            try {
                for (int i = 0; i < values.size(); i++) adaptors.get(i).set(ps, values.get(i), i + 1);
                ints[0] = ps.executeUpdate();
            } finally {
                Daos.safeClose(ps);
            }
        }
    });
    return ints[0];
}
Also used : Chain(org.nutz.dao.Chain) ConnCallback(org.nutz.dao.ConnCallback) ValueAdaptor(org.nutz.dao.jdbc.ValueAdaptor) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) DaoException(org.nutz.dao.DaoException) MappingField(org.nutz.dao.entity.MappingField) DaoException(org.nutz.dao.DaoException) SQLException(java.sql.SQLException)

Aggregations

Connection (java.sql.Connection)11 ConnCallback (org.nutz.dao.ConnCallback)11 SQLException (java.sql.SQLException)7 DaoException (org.nutz.dao.DaoException)5 PreparedStatement (java.sql.PreparedStatement)4 ArrayList (java.util.ArrayList)3 Test (org.junit.Test)3 MappingField (org.nutz.dao.entity.MappingField)3 ResultSet (java.sql.ResultSet)2 Statement (java.sql.Statement)2 HashSet (java.util.HashSet)2 Chain (org.nutz.dao.Chain)2 JdbcExpert (org.nutz.dao.jdbc.JdbcExpert)2 ValueAdaptor (org.nutz.dao.jdbc.ValueAdaptor)2 DatabaseMetaData (java.sql.DatabaseMetaData)1 ResultSetMetaData (java.sql.ResultSetMetaData)1 Set (java.util.Set)1 DataSource (javax.sql.DataSource)1 Dao (org.nutz.dao.Dao)1 DatabaseMeta (org.nutz.dao.DatabaseMeta)1