hibernate的核心类和接口
Configuration 类
1. 读取hibernate.cfg.xml
2. 管理对象关系映射文件 <mapping resource=””>
3. 加载hibernate 的驱动,url ,用户..
4. 管理hibernate配置信息
① hibernate.cfg.xml
② 对象关系映射文件
③ SessionFactory (会话工厂)
1. 可以缓存sql语句和数据(称为session级缓存)!!
2. 是一个重量级的类,因此我们需要保证一个数据库,对应一个SessionFactroy
Session(会话)接口
①Session一个实例代表与数据库的一次操作
(当然一次操作可以是crud组合)
②Session实例通过SessionFactory获取,用完
需要关闭。
③Session是线程不同步的(不安全),因此要保证
在同一线程中使用,可以用getCurrentSessiong()。
④Session可以看做是持久化管理器,它是与持久
化操作相关的接口
Configuration cf=new Configuration().configure();
SessionFactory sf=cf.buildSessionFactory();
Session s=sf.getCurrentSession();
//或者是: Session s=sf.openSession();
通过SessionFactory 获取 Session的两钟方法
openSession() and getCurrentSession();
1. openSession() 是获取一个新的session
我们可以通过session的hash值来得知
Session s1=HibernateUtil.openSession();
Session s2=HibernateUtil.openSession();
Session s3=HibernateUtil.getCurrentSession();
Session s4=HibernateUtil.getCurrentSession();
System.out.println(s1.hashCode()+" "+s2.hashCode());
System.out.println(s3.hashCode()+" "+s4.hashCode());
2. getCurrentSession () 获取和当前线程绑定的session,换言之,在同一个线程中,我们获取的session是同一session,这样可以利于事务控制
如果希望使用getCurrentSession 需要配置 hibernate.cfg.xml中配置.
<property name="current_session_context_class"><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">Jta|Thread|custom</span></property>
3. 如何选择
原则:
①如果需要在同一线程中,保证使用同一个Session则,使用getCurrentSession()
②如果在一个线程中,需要使用不同的Session,则使用opentSession()
4. 通过 getCurrentSession() 获取的session在事务提交后,会自动关闭,通过openSession()获取的session则必须手动关闭
5. 如果是通过getCurrentSession() 获取 sesssion ,进行查询需要事务提交.
在 SessionFactory启动的时候,Hibernate 会根据配置创建相应的 CurrentSessionContext,在getCurrentSession()被
调用的时候,实际被执行的方法是
CurrentSessionContext.currentSession()。在
currentSession()执行时,如果当前Session为空,currentSession会调用SessionFactory的openSession。