1、Configuraion类
a) 负责管理hibernate的配置信息
b) 读取hibernate.cfg.xml
c) 加载hibernate.cfg.xml配置文件中配置的驱动,url,用户名,密码,连接池。
d) 管理*.hbm.xml对象关系文件。
- 示例:Configurationconfiguration = new Configuration().configure();
2、SessionFactory接口
a) 缓存sql语句和其他数据
b) 重量级的类,一般是单例模式保证只有一个SessionFactory实例
- public final class SessionUtils {
- private static SessionFactory sessionFactory = null;
- private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
- private SessionUtils() {
- }
- static{
- sessionFactory=new Configuration().configure().buildSessionFactory();
- }
- //获取新的session
- public static Session OpenSession(){
- return sessionFactory.openSession();
- }
- //获取和线程相关的session
- public static Session getCurrentSession(){
- Session session = threadLocal.get();
- if (session==null) {
- session = sessionFactory.openSession();
- threadLocal.set(session);
- }
- return session;
- }
- }
c) 一个数据库创建一个SessionFactory
d) 通过SessionFactory接口获取Session实例
· openSession() 是获取一个新的session
· getCurrentSession ()获取和当前线程绑定的session,在同一个线程中,我们获取的session是同一session,这样可以利于事务控制。
使用需要配置:
- <property name="current_session_context_class">thread</property>
用下面代码测试:
- //Session s1 = MySessionFactory.getsSessionFactory().getCurrentSession();
- //Session s2 = MySessionFactory.getsSessionFactory().getCurrentSession();
- Session s1 = MySessionFactory.getsSessionFactory().openSession();
- Session s2 = MySessionFactory.getsSessionFactory().openSession();
- System.out.println(s1.hashCode()+" "+s2.hashCode());
· 通过getCurrentSession()获取的session在事务提交后,会自动关闭,通过openSession()获取的session则必须手动关闭。
3、session接口
它的主要功能和作用是:
a) Session一个实例代表与数据库的一次操作(当然一次操作可以是crud组合)
b) Session实例通过SessionFactory获取,用完需要关闭。
c) Session是线程不同步的(不安全),因此要保证在同一线程中使用,可以用getCurrentSessiong()。
d) Session可以看做是持久化管理器,它是与持久化操作相关的接口
get和load方法比较
1) 如果查询不到数据,get 会返回 null,但是不会报错, load 如果查询不到数据,则报错ObjectNotFoundException
2) 使用get 去查询数据,(先到一级/二级)会立即向db发出查询请求(select ...), 如果你使用的是 load查询数据,(先到一级、二级)即使查询到对象,返回的是一个代理对象,如果后面没有使用查询结果,它不会真的向数据库发select ,当程序员使用查询结果的时候才真的发出select ,这个现象称为懒加载(lazy)
3) 通过修改配置文件,可以取消懒加载
- <class name="Employee" lazy="false" table="employee">
4、query接口
通过query可以完成更加复杂的查询任务.
例子说明:
- public static void main(String[] args) {
- Session session = SessionUtils.getCurrentSession();
- Transaction transaction = null;
- try {
- transaction = session.beginTransaction();
- //Employee是类名不是表名
- Query query = session.createQuery("from Employee where id=1");
- //封装
- List<Employee> list = query.list();
- for (Employee employee : list) {
- System.out.println(employee.getName());
- }
- transaction.commit();
- } catch (Exception e) {
- if (transaction!=null) {
- transaction.rollback();
- }
- throw new RuntimeException(e.getMessage());
- }
- }
主要文件
a) hibernate.cfg.xml指定各个类的参数,在src下,指定连接数据库的驱动,用户名,密码,url,连接池。指定对象管理映射的位置。
b) *.hbm.xml对象管理映射文件