Linux 拨号vps windows公众号手机端

Java Hibernate使用SessionFactory创建Session案例详解

lewis 7年前 (2018-12-04) 阅读数 10 #程序编程
文章标签 Java

下面是一个使用Hibernate的SessionFactory创建Session的Java案例:

首先,你需要引入Hibernate的相关依赖。在Maven项目中,在pom.xml文件中添加以下依赖:

<dependencies>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>5.4.32.Final</version>

</dependency>

</dependencies>

接下来,创建一个Hibernate配置文件 hibernate.cfg.xml,指定数据库连接和其他Hibernate配置信息。例如:

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEhibernate-configurationPUBLIC

"-//Hibernate/HibernateConfigurationDTD3.0//EN"

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!--数据库连接配置-->

<propertyname="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

<propertyname="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>

<propertyname="hibernate.connection.username">root</property>

<propertyname="hibernate.connection.password">password</property>

<!--Hibernate配置-->

<propertyname="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

<propertyname="hibernate.show_sql">true</property>

</session-factory>

</hibernate-configuration>

在代码中,我们使用org.hibernate.cfg.Configuration类加载Hibernate配置并构建SessionFactory。然后使用SessionFactory创建Session对象。

importorg.hibernate.Session;

importorg.hibernate.SessionFactory;

importorg.hibernate.cfg.Configuration;

publicclassHibernateExample{

publicstaticvoidmain(String[]args){

//加载Hibernate配置文件

Configurationconfiguration=newConfiguration();

configuration.configure("hibernate.cfg.xml");

//获得SessionFactory

SessionFactorysessionFactory=configuration.buildSessionFactory();

//创建Session

Sessionsession=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中执行各种数据库操作。


版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门