mysql - sql中的blob数据类型与spring中的blob数据类型相同

标签 mysql sql spring blob

我有一个服务接受 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/

相关文章:

SQL Server : multiple inserts into temp table while creating a value for each different insert

java - JSF 2.0 CDI + Spring 3.1 集成,FacesContext 在部署时为 null

mysql - 如何在 Node.js 中对 MySQL 返回结果进行嵌套

mysql - 如何根据 SQL 中的更多列删除重复行?

php - 从 3 个不同的表中获取最近的帖子,在 codeigniter 中将结果限制为 5 个

sql - 在一个查询中实现多个排序和限制

MySQL 安全模式 : What Satisfies the Requirements?

sql - 如何在 SQL 中连接浮点列?

java - 在 Jersey + Spring 框架中使用 @Autowired 时出现 NullPointerException

Spring OAuth2刷新 token -无法将访问 token 转换为JSON