Inserting Clob with NamedParameterJdbcTemplate

后端 未结 3 552
轻奢々
轻奢々 2021-01-12 20:14

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/InsertC

相关标签:
3条回答
  • 2021-01-12 20:36

    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
                }
    
    0 讨论(0)
  • 2021-01-12 20:36

    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();
    }
    
    0 讨论(0)
  • 2021-01-12 20:44

    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);
    
    0 讨论(0)
提交回复
热议问题