Hibernate中的SessionFactory是什么?如何创建?代码举例讲解

在Hibernate中,SessionFactory是获取Session实例的工厂类,代表数据库连接池。主要有以下两种方式创建SessionFactory:

  1. 通过hibernate.cfg.xml配置文件创建:
  • 这需要在 pom.xml中添加Hibernate的Maven依赖,并创建hibernate.cfg.xml配置文件。
  • Hibernate会根据配置文件自动创建SessionFactory。
    例如:
    在pom.xml中添加依赖:
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.12.Final</version>
</dependency>

在resource目录下创建hibernate.cfg.xml:

<hibernate-configuration>
    <session-factory>
        <!-- 数据库连接信息 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>

        <!-- 可选配置 --> 
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    </session-factory>
</hibernate-configuration>

然后在代码中通过 org.hibernate.SessionFactory 获取SessionFactory对象。

  1. 通过Configuration对象创建:
  • 这需要通过Configuration对象设置Hibernate配置信息,然后调用buildSessionFactory()方法创建SessionFactory。
    例如:
Configuration config = new Configuration();
config.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
config.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/test");
config.setProperty("hibernate.connection.username", "root"); 
config.setProperty("hibernate.connection.password", "123456");

SessionFactory sessionFactory = config.buildSessionFactory();

SessionFactory是一个线程安全的对象,通常我们创建一个单例的SessionFactory。
SessionFactory对象是Hibernate架构的基石,理解其作用和创建方式是入门Hibernate的第一步。掌握构建SessionFactory可以让我们在项目中快速配置Hibernate,获得数据库连接资源,为业务实现提供支持。这也是评价一个Hibernate工程师的必备技能。