我有一个服务接受 post 请求并获取正文中的数据并将其保存在 MySQL 数据库中。我在 MySQL 中有一个 blob 数据类型,并且我试图将此类数据保存在 spring Blob 数据类型中。这是正确的方法吗?
编辑:我正在使用 hibernate 将数据存储在 mysql 中
最佳答案
如果您使用 Spring JdbcTemplate,那么它可以与 JDBC 中的 Blob 类型配合良好。这是一个例子:
数据库架构:
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代码:
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());
}
}
}
关于mysql - sql中的blob数据类型与spring中的blob数据类型相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32244768/