当我将Hibernate的版本从3.6.8.final更新到4.0.0.final时,我收到了关于此行中已弃用的方法buildSessionFactory()
的警告:
private static final SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
javadoc建议使用另一种方法
buildSessionFactory(ServiceRegistry serviceRegistry)
但在documentation我找到了弃用的变体:(
你能帮助我解决这个小小的误解吗?
答案 0 :(得分:372)
是的,已弃用。将SessionFactory替换为以下内容:
在 Hibernate 4.0,4.1,4.2
中private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()). buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
<强>更新强>
在 Hibernate 4.3 中,ServiceRegistryBuilder 已弃用。请改用以下内容。
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
答案 1 :(得分:15)
是的,它已被弃用。 http://docs.jboss.org/hibernate/core/4.0/javadocs/org/hibernate/cfg/Configuration.html#buildSessionFactory()明确告诉您使用您找到的其他方法(buildSessionFactory(ServiceRegistry serviceRegistry)
) - 所以请使用它。
文档从发行版复制到发行版,可能还没有更新(它们不会在每个版本中重写手册) - 所以请相信Javadoc。
可以在以下网址查看此更改的具体信息:
其他一些参考资料:
答案 2 :(得分:6)
或
public class Hbutil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
private static SessionFactory configureSessionFactory() throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return configureSessionFactory();
}
}
答案 3 :(得分:5)
验证代码在Hibernate 4.3.0中有效。请注意,您可以删除XML文件名参数,或者在那里提供自己的路径。这与其他帖子类似(但是错别字更正),但这个是正确的。
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
Configuration configuration = new Configuration();
configuration.configure("/com/rtw/test/hiber/hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
答案 4 :(得分:4)
在不同版本的文档之间发现差异并不罕见。大多数开发人员将文档视为一件苦差事,他们倾向于将其删除。
根据经验,如果javadoc说一件事和一些非javadoc文档与之相矛盾,那么javadoc的可能性就更大了。程序员更有可能使代码更改保持javadoc最新...因为javadoc的“source”与代码在同一个文件中。
在@deprecated
标签的情况下,javadoc更准确是一个虚拟的确定性。开发人员在仔细考虑之后弃用了东西......并且(一般来说)他们并没有废弃它们。
答案 5 :(得分:4)
这很简单:JBoss文档并非100%完美维护。使用what the JavaDoc says:buildSessionFactory(ServiceRegistry serviceRegistry)
。
答案 6 :(得分:3)
如果您使用 Hibernate 5.2 及以上版本,则可以使用此功能:
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
// Creating a registry
registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
// Create the MetadataSources
MetadataSources sources = new MetadataSources(registry);
// Create the Metadata
Metadata metadata = sources.getMetadataBuilder().build();
// Create SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
return sessionFactory;
}
//To shut down
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
答案 7 :(得分:3)
在最新的hibernate版本 4.3.0 中创建 SessionFactory 对象的更好方法如下:
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
答案 8 :(得分:2)
是的。像下面这样,有更好的方法来引导Hibernate。
旧版Configuration
对象的功能不如从Hibernate 4开始引入的BootstrapServiceRegistryBuilder
强大。
final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
.enableAutoClose();
Integrator integrator = integrator();
if (integrator != null) {
bsrb.applyIntegrator( integrator );
}
final BootstrapServiceRegistry bsr = bsrb.build();
final StandardServiceRegistry serviceRegistry =
new StandardServiceRegistryBuilder(bsr)
.applySettings(properties())
.build();
final MetadataSources metadataSources = new MetadataSources(serviceRegistry);
for (Class annotatedClass : entities()) {
metadataSources.addAnnotatedClass(annotatedClass);
}
String[] packages = packages();
if (packages != null) {
for (String annotatedPackage : packages) {
metadataSources.addPackage(annotatedPackage);
}
}
String[] resources = resources();
if (resources != null) {
for (String resource : resources) {
metadataSources.addResource(resource);
}
}
final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder()
.enableNewIdentifierGeneratorSupport(true)
.applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE);
final List<Type> additionalTypes = additionalTypes();
if (additionalTypes != null) {
additionalTypes.stream().forEach(type -> {
metadataBuilder.applyTypes((typeContributions, sr) -> {
if(type instanceof BasicType) {
typeContributions.contributeType((BasicType) type);
} else if (type instanceof UserType ){
typeContributions.contributeType((UserType) type);
} else if (type instanceof CompositeUserType) {
typeContributions.contributeType((CompositeUserType) type);
}
});
});
}
additionalMetadata(metadataBuilder);
MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build();
final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
Interceptor interceptor = interceptor();
if(interceptor != null) {
sfb.applyInterceptor(interceptor);
}
SessionFactory sessionFactory = sfb.build();
您还可以使用JPA引导Hibernate:
PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
Map configuration = properties();
Interceptor interceptor = interceptor();
if (interceptor != null) {
configuration.put(AvailableSettings.INTERCEPTOR, interceptor);
}
Integrator integrator = integrator();
if (integrator != null) {
configuration.put(
"hibernate.integrator_provider",
(IntegratorProvider) () -> Collections.singletonList(integrator));
}
EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder =
new EntityManagerFactoryBuilderImpl(
new PersistenceUnitInfoDescriptor(persistenceUnitInfo),
configuration
);
EntityManagerFactory entityManagerFactory = entityManagerFactoryBuilder.build();
这样,您将构建EntityManagerFactory
而不是SessionFactory
。但是,SessionFactory
也扩展了EntityManagerFactory, so the actual object that's built is a
SessionFactoryImpl`。
这两种引导方法都会影响休眠行为。当使用本机引导程序时,Hibernate会以旧模式运行,该模式早于JPA。
使用JPA引导时,Hibernate将按照JPA规范运行。
这两种模式之间有一些区别:
EntityNotFoundException
,因此需要进行数据库检查。有关这些差异的更多详细信息,请查看
JpaCompliance
类。
答案 9 :(得分:1)
public class HibernateSessionFactory {
private static final SessionFactory sessionFactory = buildSessionFactory1();
private static SessionFactory buildSessionFactory1() {
Configuration configuration = new Configuration().configure(); // configuration
// settings
// from
// hibernate.cfg.xml
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
答案 10 :(得分:0)
在 Hibernate 4.2.2
中import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class Test {
public static void main(String[] args) throws Exception
{
Configuration configuration = new Configuration()
.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Users users = new Users();
... ...
session.save(users);
transaction.commit();
session.close();
sessionFactory.close();
}
}
答案 11 :(得分:0)
Tested on 4.2.7 release
package com.national.software.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import com.national.software.dto.UserDetails;
public class HibernateTest {
static SessionFactory sessionFactory;
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("user1");
Configuration config = new Configuration();
config.configure();
ServiceRegistry serviceRegistry = (ServiceRegistry) new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
sessionFactory = config.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
答案 12 :(得分:0)
这里有许多在hibernate核心框架中弃用的API。
我们创建了会话工厂,如下所示:
SessionFactory sessionFactory = new Configuration()。configure()。buildSessionFactory();
方法buildSessionFactory已从hibernate 4发行版中弃用,并被新API替换。如果您使用的是hibernate 4.3.0及更高版本,则代码必须是:
配置配置=新配置()。configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()。applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
类ServiceRegistryBuilder由4.3.0中的StandardServiceRegistryBuilder取代。看起来5.0版本中会有很多变化。对于已弃用的API以及使用的合适替代方案,仍然没有太多的清晰度。每个增量版本都会提供更多已弃用的API,它们可以对5.0版本的核心框架进行微调。
答案 13 :(得分:0)
我编辑了batbaatar above创建的方法,因此它接受Configuration对象作为参数:
public static SessionFactory createSessionFactory(Configuration configuration) {
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
factory = configuration.buildSessionFactory(serviceRegistry);
return factory;
}
在主要课程中我做了:
private static SessionFactory factory;
private static Configuration configuration
...
configuration = new Configuration();
configuration.configure().addAnnotatedClass(Employee.class);
// Other configurations, then
factory = createSessionFactory(configuration);
答案 14 :(得分:0)
public void sampleConnection()抛出异常{
Configuration cfg = new Configuration().addResource("hibernate.cfg.xml").configure();
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
Session session = sessionFactory.openSession();
logger.debug(" connection with the database created successfuly.");
}
答案 15 :(得分:0)
在hibernate 5.3.1
中,您可以尝试以下操作:
ServiceRegistry standardRegistry =
new StandardServiceRegistryBuilder().configure().build();
Metadata sources = new MetadataSources(standardRegistry).addAnnotatedClass(MyEntity.class).getMetadataBuilder().build();
SessionFactory sf = sources.buildSessionFactory();
答案 16 :(得分:0)
如果在这里有人更新到5.1之后,它是如何工作的
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
MetadataSources sources = new MetadataSources(registry);
Metadata metadata = sources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
代替休眠4.3中的以下内容
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()). buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
答案 17 :(得分:-1)
只需导入以下包
import org.hibernate.cfg.Configuration;