Beispiel #1
0
 public int update(Class<?> classOfT, Chain chain, Condition cnd) {
   if (chain.isSpecial())
     return Daos.updateBySpecialChain(this, getEntity(classOfT), null, chain, cnd);
   EntityOperator opt = _opt(classOfT);
   opt.addUpdate(chain, cnd);
   opt.exec();
   return opt.getUpdateCount();
 }
Beispiel #2
0
 public int update(String tableName, Chain chain, Condition cnd) {
   if (chain.isSpecial()) return Daos.updateBySpecialChain(this, null, tableName, chain, cnd);
   EntityOperator opt = _optBy(chain.toEntityMap(tableName));
   if (null == opt) return 0;
   opt.addUpdate(cnd);
   opt.exec();
   return opt.getUpdateCount();
 }
Beispiel #3
0
 public void insert(String tableName, Chain chain) {
   if (chain.isSpecial()) {
     Daos.insertBySpecialChain(this, null, tableName, chain);
     return;
   }
   EntityOperator opt = _optBy(chain.toEntityMap(tableName));
   if (null == opt) return;
   opt.addInsert();
   opt.exec();
 }
Beispiel #4
0
  private void _runPreparedStatement(Connection conn, DaoStatement st, Object[][] paramMatrix)
      throws SQLException {
    ValueAdaptor[] adaptors = st.getAdaptors();
    if (adaptors.length != paramMatrix[0].length)
      throw Lang.makeThrow("DaoStatement adaptor MUST same width with param matrix.");

    boolean statIsClosed = false;
    String sql = st.toPreparedStatement();
    PreparedStatement pstat = null;

    // 打印调试信息
    if (log.isDebugEnabled()) log.debug(st);

    try {
      // 创建 SQL 语句
      pstat = conn.prepareStatement(sql);

      // 就一条记录,不要批了吧
      if (paramMatrix.length == 1) {
        for (int i = 0; i < paramMatrix[0].length; i++) {
          adaptors[i].set(pstat, paramMatrix[0][i], i + 1);
        }
        pstat.execute();
        st.getContext().setUpdateCount(pstat.getUpdateCount());
        pstat.close();
        statIsClosed = true;
      }
      // 恩,批
      else {
        for (Object[] params : paramMatrix) {
          for (int i = 0; i < params.length; i++) {
            adaptors[i].set(pstat, params[i], i + 1);
          }
          pstat.addBatch(); // 需要配置一下batchSize,嘻嘻,不然分分钟爆内存!!
        }
        int[] counts = pstat.executeBatch();

        // 计算总共影响的行数
        int sum = 0;
        for (int i : counts) if (i > 0) sum += i;

        if (sum == 0) sum = pstat.getUpdateCount();

        pstat.close();
        statIsClosed = true;

        st.getContext().setUpdateCount(sum);
      }
    } finally {
      if (!statIsClosed) Daos.safeClose(pstat);
    }

    // 打印更详细的调试信息
    if (log.isTraceEnabled()) log.trace("...DONE");
  }
Beispiel #5
0
 public void insert(Class<?> classOfT, Chain chain) {
   if (chain.isSpecial()) {
     Daos.insertBySpecialChain(this, getEntity(classOfT), null, chain);
     return;
   }
   EntityOperator opt = _opt(classOfT);
   opt.myObj = chain;
   opt.addInsertSelfOnly();
   // insert(chain.toObject(classOfT));// TODO 这样的效率,未免太低了,需要改进
   opt.exec();
 }
Beispiel #6
0
 public void setupEntityField(Connection conn, Entity<?> en) {
   Statement stat = null;
   ResultSet rs = null;
   ResultSetMetaData rsmd = null;
   try {
     // 获取数据库元信息
     stat = conn.createStatement();
     rs = stat.executeQuery(createResultSetMetaSql(en));
     rsmd = rs.getMetaData();
     // 循环字段检查
     for (MappingField mf : en.getMappingFields()) {
       try {
         int ci = Daos.getColumnIndex(rsmd, mf.getColumnName());
         // 是否只读,如果人家已经是指明是只读了,那么就不要自作聪明得再从数据库里验证了
         // if (!mf.isReadonly() && rsmd.isReadOnly(ci))
         // mf.setAsReadonly();
         // 是否非空
         if (ResultSetMetaData.columnNoNulls == rsmd.isNullable(ci)) mf.setAsNotNull();
         // 枚举类型在数据库中的值
         if (mf.getTypeMirror().isEnum()) {
           if (Daos.isIntLikeColumn(rsmd, ci)) {
             mf.setColumnType(ColType.INT);
           } else {
             mf.setColumnType(ColType.VARCHAR);
           }
         }
       } catch (Exception e) {
         // TODO 需要log一下不?
       }
     }
   } catch (Exception e) {
     if (log.isDebugEnabled()) log.debugf("Table '%s' doesn't exist!", en.getViewName());
   }
   // Close ResultSet and Statement
   finally {
     Daos.safeClose(stat, rs);
   }
 }
Beispiel #7
0
 public static Chain from(Object obj, FieldMatcher fm, Dao dao) {
   final Chain[] chains = new Chain[1];
   boolean re =
       Daos.filterFields(
           obj,
           fm,
           dao,
           new Callback2<MappingField, Object>() {
             public void invoke(MappingField mf, Object val) {
               if (mf.isReadonly() || !mf.isUpdate()) return;
               if (chains[0] == null) chains[0] = Chain.make(mf.getName(), val);
               else chains[0].add(mf.getName(), val);
             }
           });
   if (re) return chains[0];
   return null;
 }
Beispiel #8
0
  private void _runStatement(Connection conn, DaoStatement st) throws SQLException {
    boolean statIsClosed = false;
    Statement stat = null;
    String sql = st.toPreparedStatement();

    // 打印调试信息
    if (log.isDebugEnabled()) log.debug(sql);

    try {
      stat = conn.createStatement();
      stat.execute(sql);
      st.getContext().setUpdateCount(stat.getUpdateCount());
      stat.close();
      statIsClosed = true;
    } finally {
      if (!statIsClosed) Daos.safeClose(stat);
    }
    // 打印更详细的调试信息
    if (log.isTraceEnabled()) log.trace("...DONE");
  }
  @SuppressWarnings("serial")
  public void init(NutConfig nc) {
    NutShiro.DefaultLoginURL = "/admin/logout";
    // 检查环境
    if (!Charset.defaultCharset().name().equalsIgnoreCase(Encoding.UTF8)) {
      log.warn("This project must run in UTF-8, pls add -Dfile.encoding=UTF-8 to JAVA_OPTS");
    }

    // 获取Ioc容器及Dao对象
    Ioc ioc = nc.getIoc();
    // 加载freemarker自定义标签 自定义宏路径
    ioc.get(Configuration.class)
        .setAutoImports(
            new HashMap<String, String>(2) {
              {
                put("p", "/ftl/pony/index.ftl");
                put("s", "/ftl/spring.ftl");
              }
            });
    ioc.get(FreeMarkerConfigurer.class, "mapTags");
    Dao dao = ioc.get(Dao.class);

    // 为全部标注了@Table的bean建表
    Daos.createTablesInPackage(dao, getClass().getPackage().getName() + ".bean", false);

    // 获取配置对象
    PropertiesProxy conf = ioc.get(PropertiesProxy.class, "conf");

    // 初始化SysLog,触发全局系统日志初始化
    ioc.get(SysLogService.class);

    // 初始化默认根用户
    User admin = dao.fetch(User.class, "admin");
    if (admin == null) {
      UserService us = ioc.get(UserService.class);
      admin = us.add("admin", "123456");
    }
    // 初始化游客用户
    User guest = dao.fetch(User.class, "guest");
    if (guest == null) {
      UserService us = ioc.get(UserService.class);
      guest = us.add("guest", "123456");
      UserProfile profile = dao.fetch(UserProfile.class, guest.getId());
      profile.setNickname("游客");
      dao.update(profile, "nickname");
    }

    // 获取NutQuartzCronJobFactory从而触发计划任务的初始化与启动
    ioc.get(NutQuartzCronJobFactory.class);

    // 权限系统初始化
    AuthorityService as = ioc.get(AuthorityService.class);
    as.initFormPackage("net.wendal.nutzbook");
    as.checkBasicRoles(admin);

    // 检查一下Ehcache CacheManager 是否正常.
    CacheManager cacheManager = ioc.get(CacheManager.class);
    log.debug("Ehcache CacheManager = " + cacheManager);
    // CachedNutDaoExecutor.DEBUG = true;

    // 启用FastClass执行入口方法
    Mvcs.disableFastClassInvoker = false;

    // 设置Markdown缓存
    if (cacheManager.getCache("markdown") == null) cacheManager.addCache("markdown");
    Markdowns.cache = cacheManager.getCache("markdown");
    if (conf.getBoolean("cdn.enable", false) && !Strings.isBlank(conf.get("cdn.urlbase"))) {
      MarkdownFunction.cdnbase = conf.get("cdn.urlbase");
    }
  }
Beispiel #10
0
  private void _runSelect(Connection conn, DaoStatement st) throws SQLException {

    Object[][] paramMatrix = st.getParamMatrix();
    // -------------------------------------------------
    // 以下代码,就为了该死的游标分页!!
    // -------------------------------------------------
    int startRow = -1;
    int lastRow = -1;
    if (st.getContext().getResultSetType() == ResultSet.TYPE_SCROLL_INSENSITIVE) {
      Pager pager = st.getContext().getPager();
      if (pager != null) {
        startRow = pager.getOffset();
        lastRow = pager.getOffset() + pager.getPageSize();
      }
    }
    // -------------------------------------------------
    // 生成 Sql 语句
    String sql = st.toPreparedStatement();
    // 打印调试信息

    ResultSet rs = null;
    Statement stat = null;
    try {

      // 木有参数,直接运行
      if (null == paramMatrix || paramMatrix.length == 0 || paramMatrix[0].length == 0) {
        if (log.isDebugEnabled()) log.debug(st);
        stat = conn.createStatement(st.getContext().getResultSetType(), ResultSet.CONCUR_READ_ONLY);
        if (lastRow > 0) stat.setMaxRows(lastRow); // 游标分页,现在总行数
        if (st.getContext().getFetchSize() > 0) stat.setFetchSize(st.getContext().getFetchSize());
        rs = stat.executeQuery(sql);
      }
      // 有参数,用缓冲语句
      else {

        // 打印调试信息
        if (paramMatrix.length > 1) {
          if (log.isWarnEnabled())
            log.warnf("Drop last %d rows parameters for:\n%s", paramMatrix.length - 1, st);
        }
        if (log.isDebugEnabled()) {
          log.debug(st);
        }

        // 准备运行语句
        ValueAdaptor[] adaptors = st.getAdaptors();
        // 创建语句并设置参数
        stat =
            conn.prepareStatement(
                sql, st.getContext().getResultSetType(), ResultSet.CONCUR_READ_ONLY);
        if (lastRow > 0) stat.setMaxRows(lastRow);
        for (int i = 0; i < paramMatrix[0].length; i++) {
          adaptors[i].set((PreparedStatement) stat, paramMatrix[0][i], i + 1);
        }
        rs = ((PreparedStatement) stat).executeQuery();
      }
      if (startRow > 0) rs.absolute(startRow);
      // 执行回调
      st.onAfter(conn, rs);
    } finally {
      Daos.safeClose(stat, rs);
    }
    // 打印更详细的调试信息
    if (log.isTraceEnabled()) log.trace("...DONE");
  }