HIbernate介绍(配置文件、HibernateSessionFactory)

1.Hibernate简介
(1)Hibernate是一款ORM框架,Object Relation Mapping
(2)ORM是指对象关系映射,可以将DB映射成object,这样程序员可以通过
对Object操作完成对DB的操作,将JDBC封装在ORM框架底层
(3)主流ORM框架有Hibernate,iBatis,JPA
2.Hibernate框架体系结构
(1)主配置文件:用于描述数据库连接信息。
hibernate.xfg.xml或者hibernate.properties
(2)映射描述文件:用于描述映射类及属性DB表和字段之间的对应关系
*.hbm.xml
(3)映射类文件:User.java
(4)主要API组件
a.Configuration:用于加载主配置文件,获取数据库连接
b.SessionFactory:用于创建Session对象,封装了映射了信息,以及定义的sql
c.Session:用于对象操作,完成增删改查操作
d.Transaction:用于事务处理。进行增删改查操作时需要使用,因为Hibernate自动
     提交功能是关闭的
   e.Query:用于执行HQL查询语句。HQL属于面向对象查询语句,
     语句中没有表名和字段名

3.hibernate.xfg.xml文件解读
<?xml version='1.0' encoding='UTF-8'?>
	<!DOCTYPE hibernate-configuration PUBLIC
			  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
			  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
	
	<!-- Generated by MyEclipse Hibernate Tools.                   -->
	<hibernate-configuration>
	
		<session-factory>
			<property name="connection.username">scott</property>
			<property name="connection.url">jdbc:oracle:thin:@localhost:1521:chinasei</property>
			<property name="dialect">org.hibernate.dialect.OracleDialect</property>
			<property name="myeclipse.connection.profile">Oracle</property>
			<property name="connection.password">tiger</property>
			<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
			<mapping resource="com/chinasei/hibernate/model/School.hbm.xml" />
			<mapping resource="com/chinasei/hibernate/model/Student.hbm.xml" />    	
		</session-factory>
	
	</hibernate-configuration>



该文件主要配置数据库的连接、映射文件的初始化、数据库方言信息及缓存设置等内容信息。
在property属性中,注意以下几个属性:
a.myeclipse.connection.profile:表示数据库的连接名,可以任意指定。
b.dialect:sql方言,根据所使用的数据库及版本不同而不同。
    c.mapping resource:数据表的映射文件,会根据提供路径进行查找。值得注意的是,对于包名称com.chinasei.hibernate中的“.”,一律要换成“/”,即com/chinasei/hibernate。
    
    
4.HibernateSessionFactory.java
在Hibernate中,数据库的操作是通过org.hibernate.Session(注意不是web中的HttpSession)来实现的,而Session是由org.hibernate.SessionFactory来管理的。该类是用来生成Sesssion的,负责把生成Session的过程进行优化,并保证获得的Session对象是线程安全的,处理并发访问时不会出现问题。该类的结构如下:

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {

	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;
    private static Configuration configuration = new Configuration();
    private static String CONFIG_FILE_LOCATION = "/com/fcy/hibernate/hibernate.cfg.xml";
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
	
    private HibernateSessionFactory() {
    	
    }
	
    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;
    }

	
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}
	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

注意:该文件可以由MyEclipse自动生成,不需要开发人员编写。

5.Session部分方法介绍
HIbernater操作数据的接口主要是org.hibernate.Session,介绍几种数据库操作方法:

void		 delete(Object object) 					  数据删除															   
void 		 delete(String entityName, Object object) 数据删除															   					
Serializable save(Object object)  					    数据保存(由于实体类实现了Serializable接口,故可以用实体类接收返回值)
Serializable save(String entityName, Object object)   数据保存(由于实体类实现了Serializable接口,故可以用实体类接收返回值) 
void 		 update(Object object) 					  数据修改															  	
void 		 update(String entityName, Object object) 数据修改	

以上方法实现了数据库的删除、添加、修改,以上方法在使用时需要用到事务处理,具体操作如下:

	访问属性  返回值类型  方法名(参数){
		(1)获得Session对象
		try{
			(2)开始事务
			(3)调用Session对象的数据操作方法
			(4)提交事务
		}catch(RuntimeException re){
			if(事务不为空){
				(5)事务回滚
			}
			throw re;
		}finally{
			(6)关闭Session对象
		}
	}
	//示例
	public void save(Student transientInstance){
		log.debug("save Student instance");
		Session session=getSession();			//获取Session对象
		Transaction tx=null;
		try{
			tx=session.beginTransaction();		//开始事务
			session.save(transientInstacne);	//[---调用session对象的数据操作方法--]
			tx.commit();						//提交事务
			log.debug("save successful");				
		}catch(RuntimeException re){
			log.error("save failed",re);
			if(tx!=null){						//如果事务不为空
				tx.rollback();					//事务回滚
			}
			throw re;
		}finally{
			session.close();					//关闭session对象
		}
	
	}
若在Hibernate中使用查询功能,则使用HQL查询语句,或Criteria查询。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值