网上有好多blob与byte[]互相转换的代码,但是很难找到流直接写入到数据库的。显然流写入效率更高,内存占用更少(不需要把所有数据放到内存里面),以下便是代码(基于Spring Data JPA的版本的 JDBC的话实现类同)
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
@Component
public class BlobUtil {
private final static Logger logger = LoggerFactory.getLogger(BlobUtil.class);
@Autowired
private EntityManager entityManager;
private Session session;
@PostConstruct
public void init() {
entityManager = entityManager.getEntityManagerFactory().createEntityManager();
session = entityManager.unwrap(Session.class);
}
public InputStream getStream(Blob blob) {
try {
if (blob != null) {
return blob.getBinaryStream();
}
} catch (SQLException e) {
logger.error("转化出现错误 {}", e);
}
return null;
}
public Blob getBlob(InputStream inputStream) {
if (inputStream != null) {
try {
return Hibernate.getLobCreator(session).createBlob(inputStream, inputStream.available());
} catch (IOException e) {
logger.error("转化出现错误 {}", e);
}
}
return null;
}
}