通过示例在Java中构建Hibernate SessionFactory的3种方法
如果您使用的是Hibernate核心框架,则需要先建立一个SessionFactory,然后才能开始进行任何数据持久化。 顾名思义,SessionFactory产生了Hibernate会话,没有会话,您将无法执行任何创建,更新,检索或删除操作,这几乎使数据库层变得毫无意义。 对于那些需要使用Hibernate框架构建企业解决方案的人,他们可以采用几种方法来构建Hibernate SessionFactory,其中三种最受欢迎的选择是:
- 使用hibernate.cfg.xml文件构建Hibernate SessionFactory
- 使用Metatada和ServiceRegistry类在Hibernate中创建SessionFactory
- 作弊并从JPA的EntityManager中获取Hibernate SessionFactory
Hibernate中的SessionFactory是什么?
Hibernate SessionFactory是JBoss持久性框架的类库中最重要的组件。 SessionFactory在启动时会引导整个数据持久层,因为它可以处理重要的数据库连接性任务,连接池,线程池,JNDI交互,如果持久实体需要它甚至可以创建数据库表。 但最重要的是,Hibernate中的SessionFactory负责创建Session对象。 Hibernate会话提供了诸如保存,删除和更新之类的方法,所有这些方法都用于对SessionFactory连接到的数据库执行基于CRUD的操作。 大多数应用程序都会创建一个Hibernate SessionFactory单例,并在应用程序的生命周期中对其进行缓存,因为创建对象会占用大量资源。
Hibernate是JBoss对Java Persistence API(JPA)的实现,大多数应用程序都不直接与Hibernate类进行交互。 SessionFactory的JPA伴随类是EntityManagerFactory,建议现代应用程序尽可能与JPA API进行交互。 但是,有时需要Hibernate SessionFactory,因此可以通过以下三种方法创建它:
1.使用hiberante.cfg.xml构建SessionFactory
我从来都不是XML配置文件的忠实拥护者 。 我更喜欢将配置编码在Java源文件中。 但是用于构建Hibernate SessionFactory的传统且最常见的方法是利用hibernate.cfg.xml文件。
可与Hibernate 5.4版一起使用并利用最新MySQL 8驱动程序的现代hibernate.cfg.xml文件如下:
<? xml version ="1.0" encoding ="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> < hibernate-configuration > < session-factory > < property name ="connection.driver_class">com.mysql.cj.jdbc.Driver</property> <!-- property name="connection.driver_class">com.mysql.jdbc.Driver</property --> < property name ="connection.url">jdbc:mysql://localhost/hibernate_examples</property> < property name ="connection.username">root</property> < property name ="connection.password">password</property> < property name ="connection.pool_size">3</property> < property name ="dialect">org.hibernate.dialect.MySQL8Dialect</property> < property name ="current_session_context_class">thread</property> < property name ="show_sql">true</property> < property name ="format_sql">true</property> < property name ="hbm2ddl.auto">update</property> <!-- mapping class="com.mcnz.jpa.examples.Player" / --> </ session-factory > </ hibernate-configuration >
将配置文件保存到类路径后,您可以使用以下代码创建Hibernate SessionFactory:
public static Session getCurrentSessionFromConfig() { // SessionFactory in Hibernate 5 example Configuration config = new Configuration(); config.configure(); // local SessionFactory bean created SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.getCurrentSession(); return session; }
2.创建没有XML的Hibernate SessionFactory
我个人的偏爱是不惜一切代价避免使用XML,这就是为什么我总是喜欢务实地做事。 在这个Hibernate SessionFactory示例中,您将看到以前以XML存储的所有信息,这些信息已保存到Java HashMap中并传递给ServiceRegistry。 然后,将Hibernate ServiceRegistry与有关域模型中各种JPA注释类的元数据合并,然后通过这种结合,我们构建一个Hibernate SessionFactory-不需要hibernate.cfg.xml。
public static Session getCurrentSession() { // Hibernate 5.4 SessionFactory example without XML Map<String, String> settings = new HashMap<>(); settings.put( "connection.driver_class", "com.mysql.jdbc.Driver" ); settings.put( "dialect", "org.hibernate.dialect.MySQL8Dialect" ); settings.put( "hibernate.connection.url", "jdbc:mysql://localhost/hibernate_examples" ); settings.put( "hibernate.connection.username", "root" ); settings.put( "hibernate.connection.password", "password" ); settings.put( "hibernate.current_session_context_class", "thread" ); settings.put( "hibernate.show_sql", "true" ); settings.put( "hibernate.format_sql", "true" ); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(settings).build(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); // metadataSources.addAnnotatedClass(Player.class); Metadata metadata = metadataSources.buildMetadata(); // here we build the SessionFactory (Hibernate 5.4) SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); Session session = sessionFactory.getCurrentSession(); return session; }
3.从JPA的EntityManager获取本地SessionFactory bean
如果您使用的是JPA,则可以使用一个巧妙的小技巧从JPA的EntityManager中获取Hibernate SessionFactory。 首先,您可以通过快速的包装方法调用从JPA EntityManager获得Hibernate会话。 然后调用Hibernate Session的getSessionFactory()方法。 这是一个偷偷摸摸的工作,但是如果您执行的大多数数据持久性工作都利用了标准API并且仅需要偶尔访问Hiberante SessionFactory,那么这是有道理的。
public static SessionFactory getCurrentSessionFromJPA() { // JPA and Hibernate SessionFactory example EntityManagerFactory emf = Persistence.createEntityManagerFactory(" jpa-tutorial "); EntityManager entityManager = emf.createEntityManager(); // Get the Hibernate Session from the EntityManager in JPA Session session = entityManager.unwrap(org.hibernate.Session. class ); SessionFactory factory = session.getSessionFactory(); return factory; }
对于大多数软件开发,最好坚持使用标准JPA API 。 但是,很高兴知道,如果您确实需要在代码中构建Hibernate SessionFactory,则有多种选择可供选择。
您可以在GitHub上找到此Hibernate Session示例的代码。