How can I obtain a session object in Hibernate?
To obtain a Session object in Hibernate, you can create it through the SessionFactory. The SessionFactory is one of the core interfaces in Hibernate, responsible for creating and managing Session objects.
Here is an example code for obtaining SessionFactory and Session objects:
- Obtaining the SessionFactory object:
Configuration configuration = new Configuration().configure(); // 加载Hibernate配置文件
SessionFactory sessionFactory = configuration.buildSessionFactory(); // 创建SessionFactory对象
- Obtain the Session object:
Session session = sessionFactory.openSession(); // 打开一个Session对象
Now you can perform various CRUD operations and other Hibernate operations using the session object.
Remember to close the Session object promptly when it is no longer needed.
session.close();