Hi guys,
I am new to Spring and DAOs.
I have a question regarding the best way to save the BLOBs.
I have used the following two methods, and both have saved the BLOBs correctly, because when I retrieve them they are not corrupted.
Method 1
Method 2Code:public void setFile(FileItem item) { InputStream inputStream; try { inputStream = item.getInputStream(); String id = GuidGenerator.generate(); StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO Files("); sql.append("id,fname,fileObj)VALUES("); sql.append("?,?,?)"); Object[] parameters = new Object[] { id, item.getName(), inputStream }; int types[] = new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARBINARY }; this.getJdbcTemplate().update(sql.toString(), parameters, types); } catch (IOException e) { e.printStackTrace(); } }
I am using the following method to retrieve the BLOBs and get the byte[] which is used to write the file on the disk, and the files are not corrupt.Code:public void setAttachmentBlob(FileItem item) throws IOException { final InputStream iStream = item.getInputStream(); final long size = item.getSize(); final String id = GuidGenerator.generate(); final String name=item.getName(); StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO Files("); sql.append("id,fname,fileObj)VALUES("); sql.append("?,?,?)"); PreparedStatementCallback action = new AbstractLobCreatingPreparedStatementCallback(lobhandler) { protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { ps.setString(1, id); ps.setString(2, name); lobCreator.setBlobAsBinaryStream(ps, 3, iStream, (int) size); } }; this.getJdbcTemplate().execute(sql.toString(), action); }
So, again the question is which is a better way to save a BLOB, Method1 or Method2, and why?Code:public byte[] getAttachmentWithBlob(String id) throws IOException { final DefaultLobHandler lobHandler = new DefaultLobHandler(); StringBuffer sql = new StringBuffer(); sql.append("Select FILEOBJ from Files"); sql.append(" where id=\'"); sql.append(id); sql.append("\'"); RowMapper rowMapper = new RowMapper() { public Object mapRow(ResultSet rs, int arg1) throws SQLException { byte[] blobBytes = lobHandler.getBlobAsBytes(rs, "fileObj"); return blobBytes; } }; byte[] byteStream = null; try { byteStream = (byte[]) this.getJdbcTemplate().queryForObject(sql.toString(), rowMapper); } catch (Exception e) { } return byteStream; }
Any ideas and suggestions are appreciated.
Regards


Reply With Quote