【发布时间】:2016-11-04 20:13:29
【问题描述】:
我有这个实体类
@Entity
public class ScannedFile {
@Column(nullable = true)
private Blob content;
@Column(nullable = true)
private byte[] photo;
}
我试图将图像文件保存在数据库中。我找到了两种解决方案,并且都尝试过。但它们都不适合我。这是我尝试过的
1.使用字节数组
private Part file1;
public String upload() throws IOException{
InputStream inputStream = file1.getInputStream();
ScannedFile created = new ScannedFile();
created.setId(this.scannedFile.getId());
byte[] photo = IOUtils.toByteArray(inputStream);
created.setPhoto(photo);
ScannedFile newScannedFile = this.scannedFileRepository.save(created);
}
问题:上传的照片没有保存在数据库中。但它也没有给出任何错误。我在这里想念什么。
2。使用 blob
private static void initSession() {
Configuration configuration = new Configuration().configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
session.beginTransaction();
}
private static void endSession() {
session.getTransaction().commit();
session.close();
StandardServiceRegistryBuilder.destroy(serviceRegistry);
}
private Part file1;
public String upload() throws IOException{
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
InputStream inputStream = file1.getInputStream();
Blob blob = Hibernate.getLobCreator(session).createBlob(inputStream, 200);
ScannedFile created = new ScannedFile();
created.setContent(blob);
ScannedFile newScannedFile = this.scannedFileRepository.save(created);
endSession();
}
问题:我收到此错误hibernate.cfg.xml not found。但我真的不想使用这个 xml 文件。那么我怎样才能摆脱这个错误并将上传的图像保存在数据库中。
注意:我现在正在学习 spring 和 jsf 几天。我在同一个应用程序中同时使用 jsf 和 spring。我也在用h2数据库。
【问题讨论】:
-
你能描述一下你在这里使用的
Table吗? -
ScannedFile 是表。我从 h2 控制台检查了它
-
您也可以观看此视频说明在数据库中添加BLOB youtu.be/JQz_8dkLyJ8