Java Code Examples for org.springframework.jdbc.core.JdbcTemplate#queryForMap()

The following examples show how to use org.springframework.jdbc.core.JdbcTemplate#queryForMap() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JDBCTemplateTest.java    From tddl with Apache License 2.0 8 votes vote down vote up
@Test
public void tractionRollBackTest() {
    JdbcTemplate andorJT = new JdbcTemplate(us);
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(us);
    TransactionStatus ts = transactionManager.getTransaction(def);

    try {
        sql = String.format("insert into %s (pk,name) values(?,?)", normaltblTableName);
        andorJT.update(sql, new Object[] { RANDOM_ID, name });
        sql = String.format("select * from %s where pk= ?", normaltblTableName);
        Map re = andorJT.queryForMap(sql, new Object[] { RANDOM_ID });
        Assert.assertEquals(name, String.valueOf(re.get("NAME")));
        // 回滚
        transactionManager.rollback(ts);
    } catch (DataAccessException ex) {
        transactionManager.rollback(ts);
        throw ex;
    } finally {
    }
    // 验证查询不到数据
    sql = String.format("select * from %s where pk= ?", normaltblTableName);
    List le = andorJT.queryForList(sql, new Object[] { RANDOM_ID });
    Assert.assertEquals(0, le.size());
}
 
Example 2
Source File: MicroMetaDao.java    From nh-micro with Apache License 2.0 6 votes vote down vote up
public MicroMetaBean getMetaBeanById(String tableName, String id) {
/*		JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
				.getDbSource(dbName);*/
		JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
		String sql = "select * from " + tableName + " where id=?";
		logger.debug(sql);
		logger.debug("["+id+"]");
		Map retMap = jdbcTemplate.queryForMap(sql, id);
		MicroMetaBean metaBean = new MicroMetaBean();
		metaBean.setId((String) retMap.get("id"));
		metaBean.setMeta_content((String) retMap.get("meta_content"));
		metaBean.setMeta_key((String) retMap.get("meta_key"));
		metaBean.setMeta_name((String) retMap.get("meta_name"));
		metaBean.setMeta_type((String) retMap.get("meta_type"));
		metaBean.setRemark((String) retMap.get("remark"));
		metaBean.setCreate_time((Date) retMap.get("create_time"));
		metaBean.setUpdate_time((Date) retMap.get("update_time"));
		return metaBean;
	}
 
Example 3
Source File: MicroMetaDao.java    From nh-micro with Apache License 2.0 6 votes vote down vote up
public MicroMetaBean getMetaBeanById(String tableName, String id) {
/*		JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
				.getDbSource(dbName);*/
		JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
		String sql = "select * from " + tableName + " where id=?";
		logger.debug(sql);
		logger.debug("["+id+"]");
		Map retMap = jdbcTemplate.queryForMap(sql, id);
		MicroMetaBean metaBean = new MicroMetaBean();
		metaBean.setId((String) retMap.get("id"));
		metaBean.setMeta_content((String) retMap.get("meta_content"));
		metaBean.setMeta_key((String) retMap.get("meta_key"));
		metaBean.setMeta_name((String) retMap.get("meta_name"));
		metaBean.setMeta_type((String) retMap.get("meta_type"));
		metaBean.setRemark((String) retMap.get("remark"));
		metaBean.setCreate_time((Date) retMap.get("create_time"));
		metaBean.setUpdate_time((Date) retMap.get("update_time"));
		return metaBean;
	}
 
Example 4
Source File: JDBCTemplateTest.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
/**
 * traction RollBack
 * 
 * @author zhuoxue
 * @since 5.0.1
 */
@Test
public void tractionRollBackTest() {
    JdbcTemplate andorJT = new JdbcTemplate(tddlDatasource);
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(tddlDatasource);
    TransactionStatus ts = transactionManager.getTransaction(def);

    try {
        sql = String.format("insert into %s (pk,name) values(?,?)", normaltblTableName);
        andorJT.update(sql, new Object[] { RANDOM_ID, name });
        sql = String.format("select * from %s where pk= ?", normaltblTableName);
        Map re = andorJT.queryForMap(sql, new Object[] { RANDOM_ID });
        Assert.assertEquals(name, String.valueOf(re.get("name")));
        // 回滚
        transactionManager.rollback(ts);
    } catch (DataAccessException ex) {
        transactionManager.rollback(ts);
        throw ex;
    } finally {
    }
    // 验证查询不到数据
    sql = String.format("select * from %s where pk= ?", normaltblTableName);
    List le = andorJT.queryForList(sql, new Object[] { RANDOM_ID });
    Assert.assertEquals(0, le.size());
}
 
Example 5
Source File: JpaApplicationTests.java    From spring-cloud-task with Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchJobApp() {
	final String INSERT_MESSAGE = "Hibernate: insert into task_run_output (";
	this.context = SpringApplication
		.run(JpaApplication.class, "--spring.datasource.url=" + DATASOURCE_URL,
			"--spring.datasource.username=" + DATASOURCE_USER_NAME,
			"--spring.datasource.driverClassName=" + DATASOURCE_DRIVER_CLASS_NAME,
			"--spring.jpa.database-platform=org.hibernate.dialect.H2Dialect");
	String output = this.outputCapture.toString();
	assertThat(output
		.contains(INSERT_MESSAGE)).as("Unable to find the insert message: " + output)
		.isTrue();
	JdbcTemplate template = new JdbcTemplate(this.dataSource);
	Map<String, Object> result = template
		.queryForMap("Select * from TASK_RUN_OUTPUT");
	assertThat(result.get("ID")).isEqualTo(1L);
	assertThat(((String) result.get("OUTPUT"))).contains("Executed at");
}
 
Example 6
Source File: CatalogExporter.java    From lemon with Apache License 2.0 6 votes vote down vote up
public File exportCatalog(File baseDir, JdbcTemplate jdbcTemplate,
        String catalogId) throws Exception {
    String sql = "select id, code, name from CMS_CATALOG where id=?";
    Map<String, Object> map = jdbcTemplate.queryForMap(sql, catalogId);
    String code = (String) map.get("code");
    String name = (String) map.get("name");
    File dir = new File(baseDir, code);
    dir.mkdirs();

    File file = new File(baseDir, code + ".properties");
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(
            new FileOutputStream(file), "UTF-8"));
    writer.println("code=" + code);
    writer.println("name=" + name);
    writer.flush();
    writer.close();

    return dir;
}
 
Example 7
Source File: CompareDetail.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Map<String, Object> mysqlDetail(JdbcTemplate jdbcTemplate, String db, String table, int id) {
  try {
    return jdbcTemplate.queryForMap(String.format("select * from %s.%s where id = %d", db, table, id));
  } catch (EmptyResultDataAccessException e) {
    return Collections.emptyMap();
  }
}
 
Example 8
Source File: DataVarUtil.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param dataSource
 * @param bizkey
 * @param bizName
 * @param bizKeyField
 * @param executionContext
 * @return
 */
public Map<String, Object> getDataValue(String dataSource, String bizkey, String bizName, String bizKeyField) {
	try {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(DBUtils.getDataSource(dataSource));
		String sql = MessageFormat.format(QUERY_DATASQL, new Object[]{"*", bizName, bizKeyField});
		return jdbcTemplate.queryForMap(sql, new Object[]{bizkey});
	} catch (Exception e) {
		throw ExceptionUtil.getException("数据变量值获取失败!", e);
	}
}
 
Example 9
Source File: ArticleExporter.java    From lemon with Apache License 2.0 5 votes vote down vote up
public void doExport(File baseDir, JdbcTemplate jdbcTemplate,
        String articleId) throws Exception {
    try {
        String sql = "select id,code,title,content from CMS_ARTICLE where id=?";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql, articleId);

        this.exportProperties(baseDir, map);
        this.exportContent(baseDir, map);
    } catch (Exception ex) {
        ex.printStackTrace();
        System.out.println("cannot find article : " + articleId);
    }
}
 
Example 10
Source File: SqlServerTestUtils.java    From CogStack-Pipeline with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String,Object> getRowInOutputTable(int primaryKey) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(targetDataSource);
    return jdbcTemplate.queryForMap("SELECT * FROM tblOutputDocs WHERE primaryKeyFieldValue = " + Integer.toString(primaryKey));
}
 
Example 11
Source File: PostGresTestUtils.java    From CogStack-Pipeline with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String,Object> getRowInOutputTable(int primaryKey) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(targetDataSource);
    return jdbcTemplate.queryForMap("SELECT * FROM tblOutputDocs WHERE primaryKeyFieldValue = " + Integer.toString(primaryKey));
}
 
Example 12
Source File: JdbcConsumerAssociationStore.java    From openid4java with Apache License 2.0 4 votes vote down vote up
public Association load ( String opUrl, String handle )
{		
	try
	{
		JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ;

		Map res = jdbcTemplate.queryForMap ( _sqlSelect, new Object[]
			{ opUrl, handle } ) ;

		String type = (String) res.get ( "type" ) ;
		String macKey = (String) res.get ( "mackey" ) ;
		Date expDate = (Date) res.get ( "expdate" ) ;

		if ( type == null || macKey == null || expDate == null )
			throw new AssociationException (
												"Invalid association data retrived from database; cannot create Association "
														+ "object for handle: "
														+ handle ) ;

		Association assoc ;

		if ( Association.TYPE_HMAC_SHA1.equals ( type ) )
			assoc = Association.createHmacSha1 (	handle,
													Base64.decodeBase64 ( macKey.getBytes ( ) ),
													expDate ) ;

		else if ( Association.TYPE_HMAC_SHA256.equals ( type ) )
			assoc = Association.createHmacSha256 (	handle,
													Base64.decodeBase64 ( macKey.getBytes ( ) ),
													expDate ) ;

		else
			throw new AssociationException (
												"Invalid association type "
														+ "retrieved from database: "
														+ type ) ;

		if ( _log.isDebugEnabled ( ) )
			_log.debug ( "Retrieved association for handle: " + handle
							+ " from table: " + _tableName ) ;

		return assoc ;
	}
	catch ( AssociationException ase )
	{
		_log.error ( "Error retrieving association from table: "
						+ _tableName, ase ) ;
		return null ;
	}
	catch ( IncorrectResultSizeDataAccessException rse )
	{
		_log.warn ( "Association not found for handle: " + handle
					+ " in the table: " + _tableName ) ;
		return null ;
	}
	catch ( DataAccessException dae )
	{
		_log.error ( "Error retrieving association for handle: " + handle
						+ "from table: " + _tableName, dae ) ;
		return null ;
	}
}
 
Example 13
Source File: JdbcConsumerAssociationStore.java    From openid4java with Apache License 2.0 4 votes vote down vote up
public Association load ( String opUrl )
{		
	try
	{
		JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ;

		Map res = jdbcTemplate.queryForMap ( _sqlSelectAlt, new Object[]
			{ opUrl } ) ;

		String handle = (String) res.get ( "handle" ) ;
		String type = (String) res.get ( "type" ) ;
		String macKey = (String) res.get ( "mackey" ) ;
		Date expDate = (Date) res.get ( "expdate" ) ;

		Association assoc ;

           if ( expDate == null || ( type == null || macKey == null ) &&
                ! Association.FAILED_ASSOC_HANDLE.equals(handle) ) {
			throw new AssociationException (
												"Invalid expiry date retrived from database; cannot create Association "
														+ "object for handle: "
														+ handle ) ;

           } else if (Association.FAILED_ASSOC_HANDLE.equals(handle)) {
               assoc = Association.getFailedAssociation(expDate);

           } else if ( Association.TYPE_HMAC_SHA1.equals ( type ) ) {
			assoc = Association.createHmacSha1 (	handle,
													Base64.decodeBase64 ( macKey.getBytes ( ) ),
													expDate ) ;

           } else if ( Association.TYPE_HMAC_SHA256.equals ( type ) ) {
			assoc = Association.createHmacSha256 (	handle,
													Base64.decodeBase64 ( macKey.getBytes ( ) ),
													expDate ) ;

           } else {
			throw new AssociationException (
												"Invalid association type "
														+ "retrieved from database: "
														+ type ) ;

           }

		if ( _log.isDebugEnabled ( ) )
			_log.debug ( "Retrieved association for handle: " + handle
							+ " from table: " + _tableName ) ;

		return assoc ;
	}
	catch ( AssociationException ase )
	{
		_log.error ( "Error retrieving association from table: "
						+ _tableName, ase ) ;
		return null ;
	}
	catch ( IncorrectResultSizeDataAccessException rse )
	{
		_log.warn ( "Association not found for opUrl: " + opUrl
					+ " in the table: " + _tableName ) ;
		return null ;
	}
	catch ( DataAccessException dae )
	{
		_log.error ( "Error retrieving association for opUrl: " + opUrl
						+ "from table: " + _tableName, dae ) ;
		return null ;
	}
}
 
Example 14
Source File: JdbcServerAssociationStore.java    From openid4java with Apache License 2.0 4 votes vote down vote up
public Association load(String handle)
{
    try
    {
        String sql = "SELECT type,mackey,expdate FROM " + _tableName +
                " WHERE handle=?";

        JdbcTemplate jdbcTemplate = getJdbcTemplate();

        Map res = jdbcTemplate.queryForMap(sql, new Object[] {handle});

        String type = (String) res.get("type");
        String macKey = (String) res.get("mackey");
        Date expDate = (Date) res.get("expdate");

        if (type == null || macKey == null || expDate == null)
            throw new AssociationException("Invalid association data " +
                    "retrived from database; cannot create Association " +
                    "object for handle: " + handle);

        Association assoc;

        if (Association.TYPE_HMAC_SHA1.equals(type))
            assoc = Association.createHmacSha1(handle,
                    Base64.decodeBase64(macKey.getBytes() ), expDate);

        else if (Association.TYPE_HMAC_SHA256.equals(type))
            assoc = Association.createHmacSha256(handle,
                    Base64.decodeBase64(macKey.getBytes() ), expDate);

        else
            throw new AssociationException("Invalid association type " +
                    "retrieved from database: " + type);

        if (DEBUG)
            _log.debug("Retrieved association for handle: " + handle +
                       " from table: " + _tableName);

        return assoc;
    }
    catch (AssociationException ase )
    {
        _log.error("Error retrieving association from table: " + _tableName, ase);
        return null;
    }
    catch (IncorrectResultSizeDataAccessException rse)
    {
        _log.warn("Association not found for handle: " + handle +
                  " in the table: " + _tableName);
        return null;
    }
    catch (DataAccessException dae)
    {
        _log.error("Error retrieving association for handle: " + handle +
                   "from table: " + _tableName, dae);
        return null;
    }
}