我有一个接受post请求并获取数据并将其保存在MySQL数据库中的服务。我在MySQL中有一个blob数据类型,我试图在Spring Blob数据类型中保存这样的数据。这是否正确?sql中的blob数据类型与blob中的弹簧相同
编辑:我使用Hibernate如果你使用Spring的JdbcTemplate将数据存储在MySQL
我有一个接受post请求并获取数据并将其保存在MySQL数据库中的服务。我在MySQL中有一个blob数据类型,我试图在Spring Blob数据类型中保存这样的数据。这是否正确?sql中的blob数据类型与blob中的弹簧相同
编辑:我使用Hibernate如果你使用Spring的JdbcTemplate将数据存储在MySQL
,然后正常工作与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());
}
}
}
在SQL和春季两个斑点是一样的,我的意思是用于同一目的 – Labeo