Hibernate工作原理(1)

这两天再看hibernate,就自己总结了hibernate对jdbc的封装过程。

1.通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件
2.由hibernate.cfg.xml中的<mapping resource="com/xx/User.hbm.xml"/>读取并解析映射信息
3.通过config.buildSessionFactory();//创建SessionFactory
4.sessionFactory.openSession();//打开Sesssion
5.session.beginTransaction();//创建事务Transation
6.persistent operate持久化操作
7.session.getTransaction().commit();//提交事务
8.关闭Session

9.关闭SesstionFactory

这里是没有使用配置文件,手写的文件:

public int updateDm_bm(String str){   int resu=0;   //获取会话工厂   SessionFactory sf=this.getSessionFactory();   //获取SessionFactory的会话。SessionFactory接口:SessionFactroy接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象   Session session=(Session)this.getSessionFactory().getCurrentSession();   sf.openSession();   //开始事务   Transaction t=session.beginTransaction();   Query query =session.createQuery(str);   //提交事务   resu=query.executeUpdate();   // Query.executeUpdate()方法返回的整型值表明了受此操作影响   return resu;   }

其实我的IDE是Myeclipes的里面有自动生成hibernate文件的工具。仔细的看看系统自动生成的代码:

配置文件:

<hibernate-configuration> <session-factory> <property name="connection.username">root</property> <property name="connection.url"> jdbc:mysql://10.5.110.239:3306/test </property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="myeclipse.connection.profile">root</property> <property name="connection.password">chen</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <mapping resource="DAO/User.hbm.xml" /> </session-factory> </hibernate-configuration>映射文件:

<hibernate-mapping> <class name="DAO.User" table="user" catalog="test"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="assigned" /> </id> <property name="username" type="java.lang.String"> <column name="username" length="32" /> </property> <property name="password" type="java.lang.String"> <column name="password" length="32" /> </property>POJO文件和DAO文件:

public void save(User transientInstance) { log.debug("saving User instance"); try { getSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } }SessionFactory和Session类文件:就是建立加载配置文件,数据库连接,打开事务等操作:

public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; }




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值