Hibernate之代码创建SessionFactory

这篇博客详细介绍了如何配置hibernate.cfg.xml文件来连接Oracle数据库,包括设置显示SQL、格式化SQL、数据库连接URL、驱动、用户名和密码等参数。同时,展示了创建HibernateSessionFactory的代码,包括SessionFactory的初始化、Session的获取与关闭,以及重建SessionFactory的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
  <!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于查错,程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。项目部署后可以设置为false,提高运行效率-->
  <property name="show_sql">true</property>
  <property name="format_sql">true</property>
  <!--设置数据库的连接url:jdbc:mysql://localhost/student,其中localhost表示mysql服务器名称,此处为本机,student是数据库名-->
  <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
  <!--配置数据库的驱动程序,Hibernate在连接数据库时,需要用到数据库的驱动程序--> 
  <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <!--连接数据库的用户名和密码-->
  <property name="connection.username">root</property>
  <property name="connection.password">root</property>
  <!--hibernate.dialect 只是Hibernate使用的数据库方言,就是要用Hibernate连接哪种类型的数据库服务器。是必须的,用户配置Hibernate使用不同的数据库类型--> 
  <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
  
  <property name="current_session_context_class">thread</property> 

  <!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。FetchSize设的越大,读数据库的次数越少,速度越快,Fetch Size越小,读数据库的次数越多,速度越慢-->  
  <!-- <property name="jdbc.fetch_size">50</property> -->

  <!--jdbc.batch_size是指Hibernate批量插入,删除和更新时每次操作的记录数。BatchSize越大,批量操作的向数据库发送Sql的次数越少,速度就越快,同样耗用内存就越大-->  
  <!-- <property name="jdbc.batch_size">23</property> -->

  <!--jdbc.use_scrollable_resultset是否允许Hibernate用JDBC的可滚动的结果集。对分页的结果集。对分页时的设置非常有帮助-->  
  <!-- <property name="jdbc.use_scrollable_resultset">false</property> -->

  <!--数据库连接池的大小-->  
  <property name="hibernate.connection.pool.size">20</property>
  
  <property name="hibernate.hbm2ddl.auto">update</property>
  
</session-factory>
</hibernate-configuration>

HibernateSessionFactory

public class HibernateSessionFactory {

	// 指定Hibernate配置文件路径
	private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	// 创建ThreadLocal对象
	private static final ThreadLocal<Session> sessionThreadLocal = new ThreadLocal<Session>();
	// 创建Configuration对象
	private static Configuration configuration = new Configuration();
	// 定义SessionFactory对象
	private static SessionFactory sessionFactory;
	// 定义configFile属性并复制
	private static String configFile = CONFIG_FILE_LOCATION;
	// 静态代码块来启动Hibernate,该类被加载时执行一次,用于创建SessionFactory。所以SessionFactory是线程安全的,只能被实例化一次.
	static {
		try {
			StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
			Metadata metadata = new MetadataSources(standardServiceRegistry).getMetadataBuilder()
					.applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
			sessionFactory = metadata.getSessionFactoryBuilder().build();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
	}

	//创建无参的HibernateSessionFactory构造方法
	private HibernateSessionFactory() {
	}

	//获得SessionFactory对象(sessionFactory的get方法)
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	//重建SessionFactory
	public static void rebuildSessionFactory() {
		synchronized (sessionFactory) {
			try {
				StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder()
						.configure(configFile).build();
				Metadata metadata = new MetadataSources(standardServiceRegistry).getMetadataBuilder()
						.applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
				sessionFactory = metadata.getSessionFactoryBuilder().build();
			} catch (HibernateException e) {
				// TODO: handle exception
				e.printStackTrace();
			}

		}
	}

	//获得Session对象
	public static Session getSession() {
		// 获得ThreadLocal对象管理的session对象
		Session session = sessionThreadLocal.get();
		try {
			// 判断Session对象是否已经存在或是打开
			if (session == null || !session.isOpen()) {
				// 如果Session对象为空或未打开,再判断sessionFactory对象是否为空
				if (sessionFactory == null) {
					// 如果sessionFactory为空,创建SessionFactory
					rebuildSessionFactory();
				}
				// 如果sessionFactory不为空,则打开Session
				session = (sessionFactory != null) ? sessionFactory.openSession() : null;
				sessionThreadLocal.set(session);
			}
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return session;
	}

	//关闭Session对象
	public static void closeSession() {
		Session session = sessionThreadLocal.get();
		sessionThreadLocal.set(null);
		try {
			if (session != null && session.isOpen()) {
				session.close();
			}
		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	//configFile 属性的set方法
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	//configuration 属性的get方法
	public static Configuration getConfiguration() {
		return configuration;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值