Reputation: 6349
I'm having a service which accepts post request and get the data in the body and save it in a MySQL DB. I'm having a blob data type in MySQL, and I am trying to save such data in spring Blob data type. Is this the right way or not?
EDIT: I am using hibernate to store data in mysql
Upvotes: 0
Views: 632
Reputation: 3605
If you are using Spring JdbcTemplate, then it works fine with Blob type in JDBC. Here is an example:
DB schema:
CREATE TABLE `imgs` (
`img_id` int(10) unsigned NOT NULL auto_increment,
`img_title` varchar(45) NOT NULL,
`img_data` blob NOT NULL,
PRIMARY KEY (`img_id`)
);
Java code:
public interface ImageDao {
public void insertImage();
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Types;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.SqlLobValue;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobHandler;
public class ImageDaoImpl implements ImageDao {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
@Override
public void insertImage() {
try {
final File image = new File("C:\\test.jpg");
final InputStream imageIs = new FileInputStream(image);
LobHandler lobHandler = new DefaultLobHandler();
jdbcTemplate.update(
"INSERT INTO imgs (img_title, img_data) VALUES (?, ?)",
new Object[] {
"test",
new SqlLobValue(imageIs, (int)image.length(), lobHandler),
},
new int[] {Types.VARCHAR, Types.BLOB});
} catch (DataAccessException e) {
System.out.println("DataAccessException " + e.getMessage());
} catch (FileNotFoundException e) {
System.out.println("DataAccessException " + e.getMessage());
}
}
}
Upvotes: 1