这两天再看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; }