Inserting Clob with NamedParameterJdbcTemplate

☆樱花仙子☆ 提交于 2020-01-23 06:16:31

问题


I usually use the lobHandler + JdbcTemplate + PreparedStatementSetter triplet to insert my Clob into the database, as I saw on http://www.java2s.com/Code/Java/Spring/InsertClobData.htm

My question is how to do this with a NamedParameterJdbcTemplate? It has no methods accepting the mysterious PreparedStatementSetter interface as a parameter.


回答1:


This works without using the PreparedStatementCallback and lobHandler, at least when inserting a string.

NamedParameterJdbcTemplate template; //= new NamedParameterJdbcTemplate(pDs);
String INSERT_STMT = "INSERT INTO MYTABLE (ID, LONG_TEXT) VALUES (:id, :clob)";
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("id", 1L, Types.NUMERIC);
paramSource.addValue("clob", "a long long text", Types.CLOB);
template.update(INSERT_STMT, paramSource);



回答2:


I do something like this, obviously we use an Oracle database if you use something else you will have to fiddle with some of the parameter. The getJdbcTemplate method is a helper method of JdbcDaoSupport (a spring helper class.)

getJdbcTemplate().execute(new ConnectionCallback() {

        public Object doInConnection(Connection con) throws SQLException, DataAccessException {

            PublishResponseObject responseObject = new PublishResponseObject();
            OracleCallableStatement ocstmt = null;
            CLOB clob = null;

            try {
                clob = createCLOB(xmlString, con);
                ocstmt = (OracleCallableStatement) con.prepareCall("{call schmea.publish(?)}");
                //When in insert mode and update By Pk is specified updates are possible and version numbers will be returned.
                ocstmt.setCLOB(1, clob);
             ...
             }
             finally {
               clob.close()
               stmt.close
            }



回答3:


I'm using Spring 2.5.6 + Oracle and for me it worked straight away.

// Inserts file into DB and returns the key for the new row
public Number insert(String filename, byte[] data) {
    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("filename", filename);
    params.addValue("data", data);

    // Returns the autogenerated ID
    KeyHolder keyHolder = new GeneratedKeyHolder();
    String[] columnNames = {"ID"};

    // This is a NamedParameterJdbcTemplate
    jdbcTemplate.update(INSERT_SQL, params, keyHolder, columnNames);

    return keyHolder.getKey();
}


来源:https://stackoverflow.com/questions/5791662/inserting-clob-with-namedparameterjdbctemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!