2015-08-27 76 views
0

我有一个接受post请求并获取数据并将其保存在MySQL数据库中的服务。我在MySQL中有一个blob数据类型,我试图在Spring Blob数据类型中保存这样的数据。这是否正确?sql中的blob数据类型与blob中的弹簧相同

编辑:我使用Hibernate如果你使用Spring的JdbcTemplate将数据存储在MySQL

+0

在SQL和春季两个斑点是一样的,我的意思是用于同一目的 – Labeo

回答

1

,然后正常工作与JDBC BLOB类型。这里有一个例子:

DB模式:

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()); 
    } 

} 
} 
+0

我使用Hibernate会它也适用于相同的数据类型 – Labeo

+0

@Labeo我想是的。 Hibernate构建在JDBC之上。因此,创建自己的Blob类型而不是重复使用JDBC是没有意义的。 –

+0

因此在sql和spring中的blob都是一样的我的意思是用于相同的目的 – Labeo