Java 类org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate 实例源码

项目:premier-wherehows    文件:AdvSearchDAO.java   
public static List<String> getTableNames(String scopes)
{
       //Logger.debug("Entering AdvSearch.java:getTableNames()");
    List<String> tables = null;
    if (StringUtils.isNotBlank(scopes))
    {
        String[] scopeArray = scopes.split(",");
        List<String> scopeList = Arrays.asList(scopeArray);
        Map<String, List> param = Collections.singletonMap("scopes", scopeList);
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new
                NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());
        tables = namedParameterJdbcTemplate.queryForList(
                GET_DATASET_TABLE_NAMES_BY_SCOPE, param, String.class);
    }
    else
    {
        tables = getJdbcTemplate().queryForList(GET_DATASET_TABLE_NAMES, String.class);
    }

    return tables;
}
项目:premier-wherehows    文件:LineageDAOLite.java   
private static void assignData(LineageNodeLite node) {
    List<Map<String, Object>> rows = null;
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("urn", node.urn);
    NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());

    rows = namedParameterJdbcTemplate.queryForList(GET_DATA_ATTR, parameters);

    for (Map<String, Object> row : rows) {
        // node only knows id, level, and urn, assign all other attributes
        JsonNode prop = Json.parse((String) row.get("properties"));
        node.description = (prop.has("description")) ? prop.get("description").asText() : "null";
        node.source = (String) row.get("source");
        node.storage_type = (String) row.get("dataset_type"); // what the js calls storage_type, the sql calls dataset_type
        node.dataset_type = (String) row.get("dataset_type");

        // check wh_property for a user specified color, use some generic defaults if nothing found
        //node.color = getColor(node.urn, node.node_type);

        //node.abstracted_path = getPostfix(node.urn);

        // set things to show up in tooltip
        node._sort_list.add("abstracted_path");
        node._sort_list.add("storage_type");
    }
}
项目:stats-alfresco-on-database    文件:LocalDaoImpl.java   
@Override
@Transactional
public void insertStatsDirLocalSize(Map<Long, Long> dirLocalSize) throws SaodException {
    NamedParameterJdbcTemplate jdbcNamesTpl = new NamedParameterJdbcTemplate(this.jdbcTemplate);

    List<MapSqlParameterSource> batchArgs = new ArrayList<>();

    for (Entry<Long, Long> e : dirLocalSize.entrySet()) {
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("node_id", e.getKey());
        parameters.addValue("local_size", e.getValue());
        batchArgs.add(parameters);
    }

    String query = sqlQueries.getQuery("insert_stats_dir_local_size.sql");
    jdbcNamesTpl.batchUpdate(query, batchArgs.toArray(new MapSqlParameterSource[dirLocalSize.size()]));
}
项目:premier-wherehows    文件:AdvSearchDAO.java   
public static List<String> getFlowNames(String applications)
{
       //ogger.debug("Entering AdvSearch.java:getFlowNames()");
    List<String> flowNames = null;
    if (StringUtils.isNotBlank(applications))
    {
        String[] appArray = applications.split(",");
        List<String> appList = Arrays.asList(appArray);
        Map<String, List> param = Collections.singletonMap("apps", appList);
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new
                NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());
        flowNames = namedParameterJdbcTemplate.queryForList(
                GET_FLOW_NAMES_BY_APP, param, String.class);
    }
    else
    {
        flowNames = getJdbcTemplate().queryForList(GET_FLOW_NAMES, String.class);
    }

    return flowNames;
}
项目:premier-wherehows    文件:LineageDAOLite.java   
private static void assignDB(LineageNodeLite node) {
    List<Map<String, Object>> rows = null;
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("urn", node.urn);
    NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());

    rows = namedParameterJdbcTemplate.queryForList(GET_DATA_ATTR, parameters);
    // node only knows id, level, and urn, assign all other attributes

    for (Map<String, Object> row : rows) {
        JsonNode prop = Json.parse((String) row.get("properties"));
        node.description = (prop.has("description")) ? prop.get("description").asText() : "null";
        node.jdbc_url = (prop.has("jdbc_url")) ? prop.get("jdbc_url").asText() : "null";
        node.db_code = (prop.has("db_code")) ? prop.get("db_code").asText() : "null";

        // check wh_property for a user specified color, use some generic defaults if nothing found
        //node.color = getColor(node.urn, node.node_type);

        // set things to show up in tooltip
        node._sort_list.add("db_code");
        //node._sort_list.add("last_modified");
    }
}
项目:premier-wherehows    文件:LineageDAOLite.java   
private static void assignGeneral(LineageNodeLite node) {
    List<Map<String, Object>> rows = null;
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("urn", node.urn);
    NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());

    rows = namedParameterJdbcTemplate.queryForList(GET_DATA_ATTR, parameters);


    for (Map<String, Object> row : rows) {
        node.name = (String) row.get("name");
        node.schema = (String) row.get("schema");

        // check wh_property for a user specified color, use some generic defaults if nothing found
        node.color = getNodeColor(node.urn, node.node_type);

        // set things to show up in tooltip
        node._sort_list.add("urn");
        node._sort_list.add("name");
    }
}
项目:spring-data-jdbc    文件:JdbcQueryLookupStrategy.java   
/**
 * Creates a {@link QueryLookupStrategy} for the given {@link EntityManager}
 * and {@link Key}.
 *
 * @param em                        must not be {@literal null}.
 * @param key                       may be {@literal null}.
 * @param extractor                 must not be {@literal null}.
 * @param evaluationContextProvider must not be {@literal null}.
 * @return
 */
public static QueryLookupStrategy create(Key key, EvaluationContextProvider evaluationContextProvider,
                                         SqlGenerator generator, NamedParameterJdbcTemplate template, RowMapper rowMapper,
                                         TableDescription tableDescription) {

    Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!");

    switch (key != null ? key : Key.CREATE_IF_NOT_FOUND) {
        case CREATE:
            return new CreateQueryLookupStrategy(generator, template, rowMapper, tableDescription);
        case USE_DECLARED_QUERY:
            return new DeclaredQueryLookupStrategy(generator, template, rowMapper, tableDescription);
        case CREATE_IF_NOT_FOUND:
            return new CreateIfNotFoundQueryLookupStrategy(generator, template, rowMapper, tableDescription);
        default:
            throw new IllegalArgumentException(String.format("Unsupported query lookup strategy %s!", key));
    }
}
项目:spring-data-jdbc    文件:JdbcRepositoryFactory.java   
@Override
protected Object getTargetRepository(RepositoryInformation metadata) {
    entityClass = metadata.getDomainType();
    @SuppressWarnings("rawtypes")
    ReflectionJdbcRepository repository = getTargetRepositoryViaReflection(metadata, entityClass);
    repository.setDataSource(datasource);
    repository.afterPropertiesSet();
    this.repository = repository;

    generator = SqlGeneratorFactory.getInstance().getGenerator(datasource);
    template = new NamedParameterJdbcTemplate((JdbcOperations) extractRepositoryField(repository, FIELD_JDBC_OPS));
    rowMapper = extractRepositoryField(repository, FIELD_ROWMAPPER);
    tableDescription = extractRepositoryField(repository, FIELD_TABLE_DESCRIPTION);

    return repository;
}
项目:wherehowsX    文件:AdvSearchDAO.java   
public static List<String> getTableNames(String scopes)
{
    List<String> tables = null;
    if (StringUtils.isNotBlank(scopes))
    {
        String[] scopeArray = scopes.split(",");
        List<String> scopeList = Arrays.asList(scopeArray);
        Map<String, List> param = Collections.singletonMap("scopes", scopeList);
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new
                NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());
        tables = namedParameterJdbcTemplate.queryForList(
                GET_DATASET_TABLE_NAMES_BY_SCOPE, param, String.class);
    }
    else
    {
        tables = getJdbcTemplate().queryForList(GET_DATASET_TABLE_NAMES, String.class);
    }

    return tables;
}
项目:wherehowsX    文件:AdvSearchDAO.java   
public static List<String> getFlowNames(String applications)
{
    List<String> flowNames = null;
    if (StringUtils.isNotBlank(applications))
    {
        String[] appArray = applications.split(",");
        List<String> appList = Arrays.asList(appArray);
        Map<String, List> param = Collections.singletonMap("apps", appList);
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new
                NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());
        flowNames = namedParameterJdbcTemplate.queryForList(
                GET_FLOW_NAMES_BY_APP, param, String.class);
    }
    else
    {
        flowNames = getJdbcTemplate().queryForList(GET_FLOW_NAMES, String.class);
    }

    return flowNames;
}
项目:common-dao    文件:QueryInterceptor.java   
public void intercept(final NamedParameterJdbcTemplate jdbcTemplate) throws Exception {
    JdbcTemplate innerJdbcTemplate = (JdbcTemplate) jdbcTemplate.getJdbcOperations();
    this.jdbcTemplate = innerJdbcTemplate;
    DataSource dataSource = (innerJdbcTemplate.getDataSource());

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(JdbcTemplate.class);
    Callback noOpCb = NoOp.INSTANCE;
    Callback[] callbacks = new Callback[]{noOpCb, this};
    enhancer.setCallbacks(callbacks);
    enhancer.setCallbackFilter(this);
    JdbcTemplate proxy = (JdbcTemplate) enhancer.create(new Class[]{DataSource.class}, new Object[]{dataSource});

    Field jdbcTemplateField = jdbcTemplate.getClass().getDeclaredField("classicJdbcTemplate");
    jdbcTemplateField.setAccessible(true);
    jdbcTemplateField.set(jdbcTemplate, proxy);
}
项目:common-dao    文件:DaoSupport.java   
@Autowired
public DaoSupport(NamedParameterJdbcTemplate jdbcTemplate,String basePackage) {
    selectSupport = new SelectSupport(jdbcTemplate);
    updateSupport = new UpdateSupport(jdbcTemplate);
    deleteSupport = new DeleteSupport(jdbcTemplate);
    insertSupport = new InsertSupport(jdbcTemplate);

    try {
        this.queryInterceptor = new QueryInterceptor(jdbcTemplate);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("hook jdbcTemplate query methid fail,", e);
    }
    this.basePackage = basePackage;
    if (StringUtil.isEmpty(basePackage)) {
        this.basePackage = "*";
    }
    List<Class<?>> entityClassList = new EntityScanner().scan(basePackage);
    for (Class<?> clazz : entityClassList) {
        getEntity(clazz);
    }
}
项目:spring-configuration-support    文件:ConfigurationDaoImpl.java   
/**
 * Init dao.
 */
protected void initDao() throws Exception {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(getDataSource());

    this.updateQuery = "UPDATE " + this.tableName
                       + " SET " + this.tableValueColumn + " = :config_value "
                       + " WHERE " + this.tableKeyColumn + " = :config_key "
                       + " AND " + this.tableEnvColumn + " = :config_env";

    this.listQuery = "SELECT "
                     + this.tableEnvColumn + ", "
                     + this.tableKeyColumn + ", "
                     + this.tableValueColumn
                     + " FROM " + this.tableName
                     + " WHERE " + this.tableEnvColumn + " = :config_env"
                     + " OR " + this.tableEnvColumn + " = :default_env_key";

    this.getQuery = "SELECT "
                    + this.tableEnvColumn + ", "
                    + this.tableKeyColumn + ", "
                    + this.tableValueColumn
                    + " FROM " + this.tableName
                    + " WHERE " + this.tableKeyColumn + " = :config_key"
                    + " AND " + this.tableEnvColumn + " = :config_env";

}
项目:Equella    文件:SqlTaxonomyDataSource.java   
SqlTaxonomyDataSource(DataSource dataSource, Map<String, String> as)
{
    this.dataSource = dataSource;
    this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

    queryGetTerm = as.get(GET_TERM.toString());
    queryGetChildTerms = as.get(GET_CHILD_TERMS.toString());
    queryGetDataForTerm = as.get(GET_DATA_FOR_TERM.toString());
    querySearchTermsLeaves = as.get(SEARCH_TERMS_LEAVES.toString());
    queryCountTermsLeaves = as.get(COUNT_TERMS_LEAVES.toString());
    querySearchTermsTopLevel = as.get(SEARCH_TERMS_TOPLEVEL.toString());
    queryCountTermsTopLevel = as.get(COUNT_TERMS_TOPLEVEL.toString());
    querySearchTermsAny = as.get(SEARCH_TERMS_ANY.toString());
    queryCountTermsAny = as.get(COUNT_TERMS_ANY.toString());
    queryGetAllDataForTerm = as.get(GET_ALL_DATA_FOR_TERM.toString());
}
项目:wayf-cloud    文件:WayfGuiceModule.java   
@Provides
@Singleton
public NamedParameterJdbcTemplate getJdbcTemplate(
        @Named("jdbc.driver") String driver,
        @Named("jdbc.username") String username,
        @Named("jdbc.password") String password,
        @Named("jdbc.url") String url,
        @Named("jdbc.maxActive") Integer maxActive,
        @Named("jdbc.maxIdle") Integer maxIdle,
        @Named("jdbc.initialSize") Integer initialSize,
        @Named("jdbc.validationQuery") String validationQuery) {
    BasicDataSource dataSource = new BasicDataSource();

    dataSource.setDriverClassName(driver);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setUrl(url);
    dataSource.setMaxActive(maxActive);
    dataSource.setMaxIdle(maxIdle);
    dataSource.setInitialSize(initialSize);
    dataSource.setValidationQuery(validationQuery);

    return new NamedParameterJdbcTemplate(dataSource);
}
项目:OperatieBRP    文件:AdministratieveHandelingJpaRepository.java   
@Override
public int zetHandelingenStatusInLevering(final Set<Long> ids) {
    if (ids.isEmpty()) {
        return 0;
    }
    final String sql = "UPDATE kern.admhnd SET statuslev = 3 WHERE id IN (:ids) AND statuslev = 1";
    final NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(masterDataSource);

    final Map<String, Object> parameters = new HashMap<>();
    parameters.put("ids", ids);
    return jdbcTemplate.update(sql, parameters);
}
项目:OperatieBRP    文件:PersoonCacheJpaRepositoryImpl.java   
@Override
public void updateAfnemerindicatieBlob(final long persoonId, final Long lockVersiePersoon, final Long afnemerindicatieLockVersie) throws BlobException {
    final List<PersoonAfnemerindicatie> afnemerindicatiesNaToevoegen = afnemerindicatieRepository.haalAfnemerindicatiesOp(persoonId);
    final AfnemerindicatiesBlob afnemerindicatiesBlob = Blobber.maakBlob(afnemerindicatiesNaToevoegen);
    LOGGER.info("Blobify persoon:{}", persoonId);
    final byte[] afnemerindicatiesBlobBytes = Blobber.toJsonBytes(afnemerindicatiesBlob);
    //lockversieafnemerindicatiege = null uit initiele vulling of nog geen afnemerindicatie aanwezig
    final String sql
            = "UPDATE kern.perscache pc "
            + "SET lockversieafnemerindicatiege = CASE WHEN lockversieafnemerindicatiege IS NOT NULL THEN lockversieafnemerindicatiege + 1 ELSE  1 END, "
            + "afnemerindicatiegegevens = :afnemerindicatiegegevens "
            + "WHERE (pc.lockversieafnemerindicatiege = :lockversieAfnemerindicatie OR pc.lockversieafnemerindicatiege is null) "
            + "AND pc.pers = :persoonId "
            + "AND EXISTS "
            + "(SELECT 1 FROM kern.pers p WHERE p.id = pc.pers AND p.lockversie = :persoonLock )";
    final NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(masterDataSource);
    final Map<String, Object> parameters = new HashMap<>();
    parameters.put("afnemerindicatiegegevens", afnemerindicatiesBlobBytes);
    parameters.put("lockversieAfnemerindicatie", afnemerindicatieLockVersie);
    parameters.put("persoonId", persoonId);
    parameters.put("persoonLock", lockVersiePersoon);
    final int rowsUpdated = jdbcTemplate.update(sql, parameters);
    if (rowsUpdated != 1) {
        throw new OptimisticLockException("PersoonCache is ondertussen gewijzigd.");
    }
}
项目:bdf2    文件:JdbcDao.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void pagingQuery(Page<?> page,String sql,String dataSourceName,Map<String,Object> parameters,RowMapper<?> mapper){
    NamedParameterJdbcTemplate namedjdbcTemplate=this.getNamedParameterJdbcTemplate(dataSourceName);            
    String querySql=this.getDialect(this.getJdbcTemplate(dataSourceName)).getPaginationSql(sql, page.getPageNo(), page.getPageSize());
    String countSql="select count(*) from ("+sql+") sub_table_alias_";
    if(parameters!=null){
        if(mapper==null){
            page.setEntities((List)namedjdbcTemplate.queryForList(querySql,parameters));
        }else{
            page.setEntities((List)namedjdbcTemplate.query(querySql,parameters,mapper));
        }
        page.setEntityCount(namedjdbcTemplate.queryForObject(countSql,parameters, Integer.class));                              
    }else{
        JdbcTemplate jdbcTemplate=this.getJdbcTemplate(dataSourceName);
        if(mapper==null){
            page.setEntities((List)jdbcTemplate.queryForList(querySql));                
        }else{
            page.setEntities((List)jdbcTemplate.query(querySql,mapper));                                
        }
        page.setEntityCount(jdbcTemplate.queryForObject(countSql, Integer.class));
    }
}
项目:bdf2    文件:JdbcDao.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void pagingQuery(Page<?> page,String sql,String dataSourceName,Map<String,Object> parameters,RowMapper<?> mapper){
    NamedParameterJdbcTemplate namedjdbcTemplate=this.getNamedParameterJdbcTemplate(dataSourceName);            
    String querySql=this.getDialect(this.getJdbcTemplate(dataSourceName)).getPaginationSql(sql, page.getPageNo(), page.getPageSize());
    String countSql="select count(*) from ("+sql+") sub_table_alias_";
    if(parameters!=null){
        if(mapper==null){
            page.setEntities((List)namedjdbcTemplate.queryForList(querySql,parameters));
        }else{
            page.setEntities((List)namedjdbcTemplate.query(querySql,parameters,mapper));
        }
        page.setEntityCount(namedjdbcTemplate.queryForObject(countSql,parameters, Integer.class));                              
    }else{
        JdbcTemplate jdbcTemplate=this.getJdbcTemplate(dataSourceName);
        if(mapper==null){
            page.setEntities((List)jdbcTemplate.queryForList(querySql));                
        }else{
            page.setEntities((List)jdbcTemplate.query(querySql,mapper));                                
        }
        page.setEntityCount(jdbcTemplate.queryForObject(countSql, Integer.class));
    }
}
项目:Gargoyle    文件:DbUtil.java   
/**
 * 첫번쨰로우의 첫번쨰 컬럼값 리턴. <br/>
 * 값이 없는경우 NULL <br/>
 * 
 * @작성자 : KYJ
 * @작성일 : 2017. 11. 27.
 * @param dataSource
 * @param sql
 * @param paramMap
 * @return
 */
public static String selectScala(DataSource dataSource, final String sql, MapSqlParameterSource paramMap) {
    String r = null;
    try {
        noticeQuery(sql);
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

        ResultSetExtractor<String> extr = new ResultSetExtractor<String>() {

            @Override
            public String extractData(ResultSet rs) throws SQLException, DataAccessException {
                if (rs.next()) {
                    return rs.getString(1);
                }
                return null;
            }
        };
        r = jdbcTemplate.query(sql, paramMap, extr);

    } catch (Exception e) {
        throw e;
    } finally {
        cleanDataSource();
    }
    return r;
}
项目:piper    文件:JdbcJobRepositoryTests.java   
@Test
public void test1 () {
  JdbcTaskExecutionRepository taskRepository = new JdbcTaskExecutionRepository();
  taskRepository.setJdbcOperations(new NamedParameterJdbcTemplate(dataSource));
  taskRepository.setObjectMapper(createObjectMapper());

  JdbcJobRepository jobRepository = new JdbcJobRepository();
  jobRepository.setJdbcOperations(new NamedParameterJdbcTemplate(dataSource));
  jobRepository.setJobTaskRepository(taskRepository);

  int pageTotal = jobRepository.findAll(1).getNumber();

  SimpleJob job = new SimpleJob();
  job.setPipelineId("demo:1234");
  job.setId("1");
  job.setCreateTime(new Date());
  job.setStatus(JobStatus.CREATED);
  jobRepository.create(job);

  Page<Job> all = jobRepository.findAll(1);
  Assert.assertEquals(pageTotal+1,all.getSize());

  Job one = jobRepository.findOne("1");
  Assert.assertNotNull(one);
}
项目:jdbc    文件:JdbcSinkIntegrationTests.java   
@Test
public void testInsertion() {
    NamedParameterJdbcOperations namedParameterJdbcOperations = new NamedParameterJdbcTemplate(jdbcOperations);
    Map<String, Object> mapA = new HashMap<>();
    mapA.put("a", "hello1");
    mapA.put("b", 42);
    Map<String, Object> mapB = new HashMap<>();
    mapB.put("a", "hello2");
    mapB.put("b", null);
    Map<String, Object> mapC = new HashMap<>();
    mapC.put("a", "hello3");
    channels.input().send(MessageBuilder.withPayload(mapA).build());
    channels.input().send(MessageBuilder.withPayload(mapB).build());
    channels.input().send(MessageBuilder.withPayload(mapC).build());
    Assert.assertThat(namedParameterJdbcOperations.queryForObject(
            "select count(*) from messages where a = :a and b = :b", mapA, Integer.class), is(1));
    Assert.assertThat(namedParameterJdbcOperations.queryForObject(
            "select count(*) from messages where a = :a and b IS NULL", mapB, Integer.class), is(1));
    Assert.assertThat(namedParameterJdbcOperations.queryForObject(
            "select count(*) from messages where a = :a and b IS NULL", mapC, Integer.class), is(1));
}
项目:stats-alfresco-on-database    文件:LocalDaoImpl.java   
@Override
@Transactional
public void insertStatsDirNoSize(List<Long> parentsid) throws SaodException {
    NamedParameterJdbcTemplate jdbcNamesTpl = new NamedParameterJdbcTemplate(this.jdbcTemplate);

    String query = sqlQueries.getQuery("insert_stats_dir_local_size.sql");

    for (Long id : parentsid) {
        if (loadRow(id) != null) {
            continue;
        }

        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("node_id", id);
        parameters.addValue("local_size", 0);
        jdbcNamesTpl.update(query, parameters);
    }
}
项目:stats-alfresco-on-database    文件:LocalDaoImpl.java   
@Override
@Transactional
public void upadteDirSumSizeZero(List<Long> parentsid) throws SaodException {
    NamedParameterJdbcTemplate jdbcNamesTpl = new NamedParameterJdbcTemplate(this.jdbcTemplate);

    List<MapSqlParameterSource> batchArgs = new ArrayList<>();

    for (Long id : parentsid) {
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("node_id", id);
        parameters.addValue("sum_size", 0);
        batchArgs.add(parameters);
    }

    String query = sqlQueries.getQuery("update_stats_dir_sum_size.sql");
    jdbcNamesTpl.batchUpdate(query, batchArgs.toArray(new MapSqlParameterSource[parentsid.size()]));
}
项目:stats-alfresco-on-database    文件:LocalDaoImpl.java   
@Override
@Transactional
public void updateParentNodeId(Map<Long, Long> nodeids) throws SaodException {
    NamedParameterJdbcTemplate jdbcNamesTpl = new NamedParameterJdbcTemplate(this.jdbcTemplate);

    List<MapSqlParameterSource> batchArgs = new ArrayList<>();

    for (Entry<Long, Long> e : nodeids.entrySet()) {
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("node_id", e.getKey());
        parameters.addValue("parent_node_id", e.getValue());
        batchArgs.add(parameters);
    }

    String query = sqlQueries.getQuery("update_parent_node_id.sql");
    jdbcNamesTpl.batchUpdate(query, batchArgs.toArray(new MapSqlParameterSource[nodeids.size()]));
}
项目:stats-alfresco-on-database    文件:LocalDaoImpl.java   
@Override
@Transactional
public List<Long> selectparentFolders(List<Long> nodesid) throws SaodException {
    if (nodesid == null || nodesid.size() == 0) {
        return Collections.emptyList();
    }

    NamedParameterJdbcTemplate jdbcNamesTpl = new NamedParameterJdbcTemplate(this.jdbcTemplate);

    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("ids", nodesid);

    String query = sqlQueries.getQuery("select_parents_folders.sql");
    final SqlRowSet queryForRowSet = jdbcNamesTpl.queryForRowSet(query, parameters);

    final List<Long> ids = new ArrayList<>();
    while (queryForRowSet.next()) {
        ids.add(queryForRowSet.getLong(1));
    }

    return ids;
}
项目:stats-alfresco-on-database    文件:AlfrescoDaoImpl.java   
@Override
@Transactional
public Map<Long, Long> selectParentNodeId(List<Long> child_id) throws SaodException {
    NamedParameterJdbcTemplate jdbcNamesTpl = new NamedParameterJdbcTemplate(this.jdbcTemplate);

    final String query = sqlQueries.getQuery("select_parent_node_id.sql");
    final Map<Long, Long> libelle = new HashMap<>();

    for (int i = 0; i < child_id.size(); i += MAX_NUM_EXP_LIST) {
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("ids", child_id.subList(i, Math.min(i + MAX_NUM_EXP_LIST, child_id.size())));

        final SqlRowSet queryForRowSet = jdbcNamesTpl.queryForRowSet(query, parameters);
        while (queryForRowSet.next()) {
            libelle.put(queryForRowSet.getLong(1), queryForRowSet.getLong(2));
        }

    }

    return libelle;
}
项目:osmp    文件:JdbcTemplateManager.java   
public void addDataSource(DataSource ds,String catalog,DBType dbType){
    if(ds == null || catalog == null || dbType == null) return;
    BaseTemplate jdbcTemplate = null;

    if(dbType.equals(DBType.SQLSERVER)){
        jdbcTemplate = new MSSQLTemplate();
    }else if(dbType.equals(DBType.MYSQL)){
        jdbcTemplate = new MysqlTemplate();
    }else{
        jdbcTemplate = new OracleTemplate();
    }
    jdbcTemplate.setOwnJdbcTemplate(new NamedParameterJdbcTemplate(ds));
    jdbcTemplate.setTransactionManager(new DataSourceTransactionManager(ds));
    //dsTransactionManager.setGlobalRollbackOnParticipationFailure(false); //指定主事务决定回滚

    templates.put(catalog.toUpperCase(), jdbcTemplate);

}
项目:Rapture    文件:PostgresHelper.java   
public static boolean tableExists(NamedParameterJdbcTemplate namedParameterJdbcTemplate, String tableName) throws PostgresException {
    String sql = "SELECT EXISTS (\n"
            + "    SELECT 1 \n"
            + "    FROM   pg_catalog.pg_class c\n"
            + "    JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"
            + "    WHERE  n.nspname = 'public'\n"
            + "    AND    c.relname = :table_name\n"
            + ")";

    SqlParameterSource paramSource = new MapSqlParameterSource("table_name", tableName);
    try {
        return namedParameterJdbcTemplate.queryForObject(sql, paramSource, Boolean.class);
    } catch (DataAccessException e) {
        throw new PostgresException(String.format("Error while checking if table [%s] exists", tableName), e);
    }
}
项目:Rapture    文件:PgIndexCreationTest.java   
private void insertValue(NamedParameterJdbcTemplate jdbcTemplate, int i) throws SQLException {
    String value = String.format("{\"id\": "
            + "\"%s\", \"max\": 2, \"message\": \"what upz\", \"lastSeen\": 12345, \"progress\": 1}", i);
    PGobject valueJson = new PGobject();
    valueJson.setType("jsonb");
    valueJson.setValue(value);
    SqlParameterSource params = new MapSqlParameterSource().addValue("keyIn", "key" + i).addValue("contentIn", valueJson);
    jdbcTemplate.update("INSERT INTO activity\n"
            + "VALUES(:keyIn, :contentIn, now());\n", params);
}
项目:spring-cloud-stream-app-starters    文件:JdbcSinkIntegrationTests.java   
@Test
public void testInsertion() {
    NamedParameterJdbcOperations namedParameterJdbcOperations = new NamedParameterJdbcTemplate(jdbcOperations);
    Map<String, Object> mapA = new HashMap<>();
    mapA.put("a", "hello1");
    mapA.put("b", 42);
    Map<String, Object> mapB = new HashMap<>();
    mapB.put("a", "hello2");
    mapB.put("b", null);
    Map<String, Object> mapC = new HashMap<>();
    mapC.put("a", "hello3");
    channels.input().send(MessageBuilder.withPayload(mapA).build());
    channels.input().send(MessageBuilder.withPayload(mapB).build());
    channels.input().send(MessageBuilder.withPayload(mapC).build());
    Assert.assertThat(namedParameterJdbcOperations.queryForObject(
            "select count(*) from messages where a = :a and b = :b", mapA, Integer.class), is(1));
    Assert.assertThat(namedParameterJdbcOperations.queryForObject(
            "select count(*) from messages where a = :a and b IS NULL", mapB, Integer.class), is(1));
    Assert.assertThat(namedParameterJdbcOperations.queryForObject(
            "select count(*) from messages where a = :a and b IS NULL", mapC, Integer.class), is(1));
}
项目:Camel    文件:ElsqlSqlProcessingStrategy.java   
@Override
public int commit(DefaultSqlEndpoint defaultSqlEndpoint, Exchange exchange, Object data, NamedParameterJdbcTemplate jdbcTemplate,
                  SqlParameterSource parameterSource, String query) throws Exception {

    final SqlParameterSource param = new ElsqlSqlMapSource(exchange, data);
    final String sql = elSql.getSql(query, new SpringSqlParams(param));
    LOG.debug("commit @{} using sql: {}", query, sql);

    return jdbcTemplate.execute(sql, param, new PreparedStatementCallback<Integer>() {
        @Override
        public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.execute();

            int updateCount = ps.getUpdateCount();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Update count {}", updateCount);
            }
            return updateCount;
        }
    });
}
项目:Camel    文件:ElsqlSqlProcessingStrategy.java   
@Override
public int commitBatchComplete(DefaultSqlEndpoint endpoint, NamedParameterJdbcTemplate namedJdbcTemplate,
                        SqlParameterSource parameterSource, String query) throws Exception {

    final SqlParameterSource param = new EmptySqlParameterSource();
    final String sql = elSql.getSql(query, new SpringSqlParams(param));
    LOG.debug("commitBatchComplete @{} using sql: {}", query, sql);

    return namedJdbcTemplate.execute(sql, param, new PreparedStatementCallback<Integer>() {
        @Override
        public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.execute();

            int updateCount = ps.getUpdateCount();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Update count {}", updateCount);
            }
            return updateCount;
        }
    });
}
项目:bamboobsc    文件:SysLoginLogSupport.java   
public static void log(String userId) {
    if ( StringUtils.isBlank(userId) ) {
        log.warn("null userId");
        return;
    }
    NamedParameterJdbcTemplate namedParameterJdbcTemplate = (NamedParameterJdbcTemplate)AppContext.getBean("namedParameterJdbcTemplate");
    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("oid", SimpleUtils.getUUIDStr());
    paramMap.put("user", userId);
    paramMap.put("cuserid", "SYS");
    paramMap.put("cdate", new Date());
    try {
        namedParameterJdbcTemplate.update("insert into tb_sys_login_log(OID, USER, CUSERID, CDATE) values(:oid, :user, :cuserid, :cdate)", paramMap);
    } catch (Exception e) {
        e.printStackTrace();
        log.error( e.getMessage().toString() );
    }       
}
项目:FinanceAnalytics    文件:DbConnector.java   
/**
 * Creates an instance.
 * 
 * @param name the configuration name, not null
 * @param dialect the database dialect, not null
 * @param dataSource the data source, not null
 * @param jdbcTemplate the JDBC template, not null
 * @param hibernateTemplate the Hibernate template, may be null
 * @param transactionTemplate the transaction template, not null
 */
public DbConnector(
    String name, DbDialect dialect, DataSource dataSource,
    NamedParameterJdbcTemplate jdbcTemplate, HibernateTemplate hibernateTemplate, TransactionTemplate transactionTemplate) {
  ArgumentChecker.notNull(name, "name");
  ArgumentChecker.notNull(dialect, "dialect");
  ArgumentChecker.notNull(dataSource, "dataSource");
  ArgumentChecker.notNull(jdbcTemplate, "JDBC template");
  ArgumentChecker.notNull(transactionTemplate, "transactionTemplate");
  _name = name;
  _dataSource = dataSource;
  _dialect = dialect;
  _jdbcTemplate = jdbcTemplate;
  _hibernateTemplate = hibernateTemplate;
  _transactionTemplate = transactionTemplate;
  _clock = new DbClock(this);  // late initialization
}
项目:nics-common    文件:NicsDaoTest.java   
private void removeTestFormData() {
    NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(dataSource);

    int formId = -1;
    try {
        formId = template.queryForObject("select formid from form where formid=:formid", 
                new MapSqlParameterSource("formid", 9999), Integer.class);
    } catch(Exception e) {
        System.out.println("Failed to get formId, not removing form!");
        return;
    }
    System.out.println("\n!!!Retrieve test form ID result: " + formId);


    int formResult = template.update("delete from form where formid=:formid",
            new MapSqlParameterSource("formid", formId));
    System.out.println("\n!!!Remove test Form result: " + formResult);
}
项目:WhereHows    文件:AdvSearchDAO.java   
public static List<String> getTableNames(String scopes)
{
    List<String> tables = null;
    if (StringUtils.isNotBlank(scopes))
    {
        String[] scopeArray = scopes.split(",");
        List<String> scopeList = Arrays.asList(scopeArray);
        Map<String, List> param = Collections.singletonMap("scopes", scopeList);
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new
                NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());
        tables = namedParameterJdbcTemplate.queryForList(
                GET_DATASET_TABLE_NAMES_BY_SCOPE, param, String.class);
    }
    else
    {
        tables = getJdbcTemplate().queryForList(GET_DATASET_TABLE_NAMES, String.class);
    }

    return tables;
}
项目:WhereHows    文件:AdvSearchDAO.java   
public static List<String> getFlowNames(String applications)
{
    List<String> flowNames = null;
    if (StringUtils.isNotBlank(applications))
    {
        String[] appArray = applications.split(",");
        List<String> appList = Arrays.asList(appArray);
        Map<String, List> param = Collections.singletonMap("apps", appList);
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new
                NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());
        flowNames = namedParameterJdbcTemplate.queryForList(
                GET_FLOW_NAMES_BY_APP, param, String.class);
    }
    else
    {
        flowNames = getJdbcTemplate().queryForList(GET_FLOW_NAMES, String.class);
    }

    return flowNames;
}
项目:smart-sync    文件:H2Test.java   
private void test() {
    try {
        super.getSrcDs().getConnection().close();
        logger.info("H2 Connection works");
        NamedParameterJdbcTemplate t=new NamedParameterJdbcTemplate(getSrcDs());
        Connection c=super.getSrcDs().getConnection();
        c.prepareStatement("drop table test if exists").execute();
        c.prepareStatement("create table test (s varchar2(10), i integer, r real )").execute();
        c.close();
        logger.info("test table creation ok");
        logger.info("Your H2 installation seems good");
    } catch (SQLException e) {
        throw new SyncException(e);
    }

}
项目:npjt-extra    文件:QueryType.java   
@SuppressWarnings("unchecked")
private static <T> AffectedRowCountAndKey<T> executeUpdateAndKeepKeys(
        String template, Method method,
        NamedParameterJdbcTemplate jdbc, SqlParameterSource parameters) {

    Class<T> keyClass = (Class<T>) ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0];

    KeyHolder keyHolder = new GeneratedKeyHolder();

    int result = jdbc.update(template, parameters, keyHolder);
    Map<String, Object> keys = keyHolder.getKeys();
    Object key;
    if (keys.size() > 1) {
        AutoGeneratedKey spec = Objects.requireNonNull(withType(method.getDeclaredAnnotations(), AutoGeneratedKey.class), "more than one key for query " + template + ": annotation @AutoGeneratedKey required");
        key = Objects.requireNonNull(keys.get(spec.value()), "the key with name " + spec.value() + " has returned null for query " + template + ": required a non null key");
    } else if (Number.class.isAssignableFrom(keyClass)) {
        Class<? extends Number> c = (Class<? extends Number>) keyClass;
        return new AffectedRowCountAndKey<>(result, (T) NumberUtils.convertNumberToTargetClass(keyHolder.getKey(), c));
    } else {
        key = keys.values().iterator().next();
    }
    return new AffectedRowCountAndKey<>(result, keyClass.cast(key));
}