Hibernate进阶

1、Hibernate执行流程

  Configuration--->SessionFaction--->Session--->(save/delete/update/get)--->Transaction--->tx.commit()--->session.close()

                         丨------------------------------丨

  Configuration来自hibernate.cfg.xml

  SessionFaction来自User.hbm.xml

  Session相当于JDBC中的Connection


 

2、Session与Connection的关系

  Session与Connection是多对一的关系,每一个Session都有一个与之对用的Connection,一个Connection可以给多个Session使用


 

3、Session的方法

  save()、update()、delete()、createQuery()


 

4、transtion简介

  hibernate对数据操作都是默认封装在事务当中,默认非自动提交,必须开启事务,对象才能保存在数据库中

  如果想让hibernate像jdbc一样自动提交事务,必须调用session 的doWordk()方法


 

5、session详解

  如何获得session?

    openSession

    getCurrentSession需要在hibernate.cfg.xml中进行配置<porperty name="hibernate.current_session_context_class">thread</oprperty>

  openSession和getCurrentSession的区别:

    1、openSession在使用完Session后需要关闭Session,如果不关闭,多次之后会导致连接池溢出

       getCurrentSession使用完后会自动关闭Session

    2、openSession每次创建新的Session对象

       getCurrentSession只创建一次Session,是一个单例模式


 6、hbm配置文件常用设置(映射文件)

  hibernate映射设置

  <hibernate-mapping

    schema="schemaName"  //模式名称

    catalog="catalogName"  //目录名称

    default-cascade="cascade_style"  //级联风格

    default-access="field|property|ClassName"  //访问策略

    default-lazy="true|false"  //加载策略

    package="packagename"  //默认包名

  />

  类设置

  <class

    name="ClassName"  //类名

    table="tableName"  //表明

    batch-size="N"  //抓取策略

    where="condtion"  //抓取条件

    entity-name="EntityName"  //一个类映射多个表

  />

  id设置

  <id 

    name="propertyName"

    type="typeName"

    column="column_name"

    length="length"

  >  

    <generator class="generatorClass">

  </id>

  主键生成策略  native  assigend


 

 7、hibernate工具类

  因为原生每次获取session对象的方法比较重复,所以封装成一个HibernateUtil类来获取session

  public class HibernateUtil{

    private static SessionFactory sessionFactory;//单例模式

    private static Session session;

    static{

      //创建Configuration对象,读取hbm.cfg.xml配置文件

      Configuration config=new Configuration().configrure();

      StandardServiceRegistryBuilder ssrb=new StadardServiceRegistryBuilder().applySettings(config.getProperties());//记录连接时服务

      StandardServiceRegistry ssr=ssrb.build();

      sessionFactory sf=config.buildSessionFactory(ssr);

    }  

    //获取SessionFactory

    public static SessionFactory getSessionFactory(){

      return sessionFactory;

    }

    //获取Session

    public static Session getSession(){

      session=sessionFactory.openSession();

      return session;

    }

    //关闭session

    public static void closeSession(){

      if(session!=null){

        session.close();

      }

    }

  }

    

  

转载于:https://www.cnblogs.com/RocketMan/p/5271226.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值