Spring JdbcTemplate - Insert blob and return generated key

后端 未结 11 1849
猫巷女王i
猫巷女王i 2020-12-15 06:06

From the Spring JDBC documentation, I know how to insert a blob using JdbcTemplate

final File blobIn = new File(\"spring2004.jpg\");
final InputStream blobIs         


        
11条回答
  •  生来不讨喜
    2020-12-15 06:12

    All of this seemed way too complicated to me. This works and is simple. It uses org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate

    import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
    import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
    import org.springframework.jdbc.core.support.SqlLobValue;
    import org.springframework.jdbc.support.lob.DefaultLobHandler;
    
    
        public void setBlob(Long id, byte[] bytes) {
            try {
                jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
                MapSqlParameterSource parameters = new MapSqlParameterSource();
                parameters.addValue("id", id);
                parameters.addValue("blob_field", new SqlLobValue(new ByteArrayInputStream(bytes), bytes.length, new DefaultLobHandler()), OracleTypes.BLOB);
                jdbcTemplate.update("update blob_table set blob_field=:blob_field where id=:id", parameters);
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    

提交回复
热议问题