繁体   English   中英

如何使用Java和JDBC向数据库发送/接收HashMap?

[英]How to send/receive HashMap to/from database using Java and JDBC?

一位同事已将Java和MySQL配置为{send / receive} = [IN / OUT]参数作为HashMap ,并将结果作为HashMap返回。

是否可以配置任何第三方软件包?

public void sendValuesTODatabase(String user_id, String userName) {          
    HashMap hm1 = new HashMap();
    hm1.put("1", user_id);       // Parameters according to the Type
    hm1.put("2", username);


    int nooftable = 3;           /* represents number of select statements used in Stored           
                                    Procedure */

    Vector vCols = new Vector();
    vCols.addElement("1");       // One Column used for selection in Mysql select query 1
    vCols.addElement("2");       // Two Column used for selection in Mysql select query 2
    vCols.addElement("1");       // one Column used for selection in Mysql select query 3

    BlobValues bls = new BlobValues();
    HashMap hmap = (HashMap)bls.getGeneric(hm1,"DB_SCHEMA_NAME.SP_PACKAGE_NAME.PROCEDURE_NAME", 
                    nooftable, vCols);

    HashMap dBResult1 = (HashMap)hmap.get("GENERICJAVA1"); // Select stmt result1 in HashMap
    HashMap dBResult2 = (HashMap)hmap.get("GENERICJAVA2"); // Select stmt result2 in HashMap
    HashMap dBResult3 = (HashMap)hmap.get("GENERICJAVA3"); // Select stmt result3 in HashMap
}

Spring Framework为这种情况提供了解决方案。

我们可以使用org.springframework.jdbc.object.StoredProcedure或org.springframework.jdbc.core.simple.SimpleJdbcCall类并将输入参数Map传递给它的execute()方法。

它返回可以迭代的输出参数Map。

下面是StoredProcedure类的示例。

@Component
public class ItemInsert extends StoredProcedure {
public static final String SPROC_NAME = "schema.oracle_pkg.proc_name";
public static final String INPUT_PARAM = "input_prm_name";
public static final String OUPUT_PARAM = "output_prm_name";

@Inject
public ItemInsert(DataSource ds) {
super(ds, SPROC_NAME);
declareParameter(new SqlParameter(INPUT_PARAM, Types.VARCHAR));
declareParameter(new SqlOutParameter(OUTPUT_PARAM, Types.NUMERIC));
compile();
}

public Item insert(Item item)
  throws DataAccessException {
Map<String, Object> inputs = new HashMap<String, Object>();
inputs.put(INPUT_PARAM, item.getSomething());
Map<String, Object> output = super.execute(inputs);
Object newId = output.get(OUTPUT_PARAM);
if (newId != null) {
  item.setId(Long.parseLong(newId.toString()));
}
return item;
}

可以在以下网址找到SimpleJdbcCall的示例: http://www.pretechsol.com/2014/04/how-to-call-stored-procedure-using.html#.VAtktsWSw1I

    SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(template)
    .withProcedureName("customerDetails");
    Map<String, Object> inParamMap = new HashMap<String, Object>();
    inParamMap.put("id", 1);
    SqlParameterSource in = new MapSqlParameterSource(inParamMap);
    Map<String, Object> simpleJdbcCallResult = simpleJdbcCall.execute(in);
    System.out.println(simpleJdbcCallResult);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM