Java Hibernate使用SessionFactory创建Session案例详解
下面是一个使用Hibernate的SessionFactory创建Session的Java案例:
首先,你需要引入Hibernate的相关依赖。在Maven项目中,在`pom.xml`文件中添加以下依赖:
```xml
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.32.Final</version>
</dependency>
</dependencies>
```
接下来,创建一个Hibernate配置文件 `hibernate.cfg.xml` ,指定数据库连接和其他Hibernate配置信息。例如:
```xml
<?xml version="1.0" encoding="UTF⑻"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration⑶.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接配置 -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<!-- Hibernate配置 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>
```
在代码中,我们使用`org.hibernate.cfg.Configuration`类加载Hibernate配置并构建SessionFactory。然后使用
SessionFactory创建Session对象。
```java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateExample {
public static void main(String[] args) {
// 加载Hibernate配置文件
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
// 取得SessionFactory
SessionFactory sessionFactory = configuration.buildSessionFactory();
// 创建Session
Session session = sessionFactory.openSession();
// 履行数据库操作
// 关闭Session
session.close();
// 关闭SessionFactory
sessionFactory.close();
}
}
```
在上述示例中,我们加载了`hibernate.cfg.xml`文件并使用`configuration.configure()`方法进行配置。然后,通过
`configuration.buildSessionFactory()`构建SessionFactory对象。
接下来,我们使用`sessionFactory.openSession()`方法创建一个新的Session对象,该对象可以用于履行与数据库相关的
操作。在完成所有数据库操作后,我们调用`session.close()`关闭Session。
最后,在利用程序结束时,我们需要调用`sessionFactory.close()`方法关闭SessionFactory。
这就是使用SessionFactory创建Session的扼要示例。你可以根据自己的需求和实际情况在Session中履行各种数据库操作。
TOP