方法 Hibernate.createBlob()
已从 Hibernate 4.0.1 中弃用并移至 Hibernate.getLobCreator(Session session).createBlob()
。我应该在方法 getLobCreator(Session session)
中传递什么的任何解决方案,即代替 Session,或显示如何使用 Spring 和 Hibernate 检索图像并将图像保存到 DB 中的任何其他解决方案。
最佳答案
根据 this easy tutorial ,
Session Object
A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.
在 Hibernate 4.0+ 中,您可以从 SessionFactory
中获取 Session
对象。让我们为此任务编写一个方便的类。
package your.company.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
ServiceRegistry registry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(registry);
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
然后:
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
byte[] bFile = /* load image into byte array */;
Blob image = Hibernate.getLobCreator(session).createBlob(bFile);
/* ? Your actions with Blob ? */
session.getTransaction().commit();
如果可行,请告诉我。
或者(假设Employee
是一个POJO,字段@Lob private byte[] photo;
,绑定(bind)到对应的表):
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
byte[] bFile = /* load image into byte array */;
Employee employee = new Employee();
employee.setPhoto(bFile);
session.save(employee);
session.getTransaction().commit();
信息来自 mkyong.com .在这里您可以找到如何将图像保存到数据库中的完整示例。以及如何检索图像的示例。
注意:对于 Hibernate 4.3+,您在 try
block 中的代码略有变化。因为类 ServiceRegistryBuilder
被替换为 StandardServiceRegistryBuilder
。
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
关于java - 方法 Hibernate.createBlob() 已从 Hibernate 4.0.1 弃用并移至 Hibernate.getLobCreator(Session session).createBlob(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18051290/