花了两天了,终于把hibernate的大部分的技术学会了, 真是不容易,学了之后发现其实hibernate也挺简单的,我的学的是版本为,hibernate2.1.7的版本的,没办法,目前手上hibernate2的资料比较多,hibernate3的资料不是很多,不过也看了下hibernate3的,差不了多少,就包名不同,不过有去掉一些东西,比如连接池dbcp的支持
session.find();也增加了对hql语句的功能,大部分能够实现sql语句同样的功能
在这次初学hibernate所用到的知识,及一些开发技巧与大家共同分享,学习hibernate有涉及到下面的最基本技术
1.如何配置hibernate.cfg.xml,包括连接池的使用
2.如何通过工具来生成*.hbm.xml
3.如何通过*.hbm.xml生成pojo,pojo是我们可以用简单的理解为set get ,虽然不是很专业,大家明白就好了
4.如何配置hibernate.cfg.xml,引入二级缓存,经常用到的是对query进行缓存,可以加入echache来实现
5. log4j使用,很多地方都有log4j.properties直接放上classpath下就能用, 不过要相关的包log4j.jar
6.实体之间的映射关系的配置one2one, many2one ,one2many ,many2many
7.hql的使用
*.hbm.xml可以用middlegen来完成任务,可以将dll生成hbm,再结合hibernate-tools将生成pojo
在使用middlegen的过程中 需要用到ant 来运行 middlegen的build.xml中的任务,这里还可以学习ant的使用
最基本的技术介绍完了,对于不是hibernate的初学者来说,上面的那些那些技巧对他来说,都不成问题了,早就会了,我就不多说了
hibernate中最经常用到的就是要连接数据库,很多初学者都会在每个测试类中用下面一段代码来完成session的创建和关闭,如:
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();如果有用到更新或者插入的时候还得用事务去提交,这里还是测试到事务的commit()和rollback()
如:
Transaction tran = null;
try...{
tran = session.beginTransaction();
//具体实现
tran.commit();
}catch(Exception e)...{
if (tran != null) ...{
try ...{
tran.rollback();
} catch (HibernateException he) ...{
he.printStackTrace();
}
} 笔者将上面那些常用方法进行封装,供需要的朋友使用
//hibernate的操作接口
package com.redsaga.quickstart.db;
import java.net.URL;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/** *//**
* hibernate的操作接口
* @author loemkie
*
*/
public class Hibernate...{
/** *//**
* Initialize the hibernate environment
* @param hibernate_cfg
* @throws HibernateException
*/
public final static Hibernate init(URL hibernate_cfg) throws HibernateException...{
return new Hibernate(hibernate_cfg);
}
/** *//**
* Initialize the hibernate environment
* @throws HibernateException
*/
public final static Hibernate init() throws HibernateException...{
return new Hibernate();
}
/** *//**
* 根据输入的配置文件初始化Hibernate
* @param cfg_path
* @throws HibernateException
*/
private Hibernate(URL hibernate_cfg) throws HibernateException...{
sessions = new ThreadLocal();
transactions = new ThreadLocal();
Configuration cfg = new Configuration();
if(hibernate_cfg!=null)...{
cfg =cfg.configure(hibernate_cfg);
}else...{
cfg=cfg.configure();
}
sessionFactory = cfg.buildSessionFactory();
this.hibernate_cfg = hibernate_cfg;
}
/** *//**
* 默认cfg_path=hibernate.hbm.xml
* @throws HibernateException
*/
private Hibernate() throws HibernateException...{
new Hibernate(null);
}
/** *//**
* 返回对应的Hibernate配置文件的路径
* @return
*/
public URL getHibernateConfig() ...{
return hibernate_cfg;
}

/** *//**
* Get a instance of hibernate's session
* @return
*/
public Session getSession()...{
if(sessions == null)
return null;
Session ssn = (Session)sessions.get();
if (ssn == null || !ssn.isOpen()) ...{
try...{
ssn = sessionFactory.openSession();
sessions.set(ssn);
}catch (Exception e) ...{
// TODO: handle exception
log.error(e.getMessage());
return null;
}
}
return ssn;
}

/** *//**
* Closes the Session local to the thread.
*/
public void closeSession()...{
if(sessions == null)
return;
// Would be written as a no-op in an EJB container with CMT
Session ssn = (Session)sessions.get();
if(ssn == null)
return;
else if(ssn.isOpen())...{
try...{
ssn.close();
}catch (Exception e) ...{
// TODO: handle exception
log.error(e.getMessage());
}
}
sessions.set(null);
}

/** *//**
* Start a new database transaction.
*/
public void beginTransaction()...{
if(transactions == null)
return;
// Would be written as a no-op in an EJB container with CMT
Transaction tx = (Transaction)transactions.get();
try...{
if (tx == null || tx.wasCommitted() || tx.wasRolledBack()) ...{
Session ssn = (Session)sessions.get();
if(ssn == null)...{
ssn = getSession();
tx = ssn.beginTransaction();
transactions.set(tx);
}
else if(ssn != null)...{
tx = ssn.beginTransaction();
transactions.set(tx);
}
}
else...{
if(tx!=null && log.isWarnEnabled())
log.warn("Trying to begin a exist transaction, nothing to do.", new Exception());
}
}catch (Exception e) ...{
// TODO: handle exception
log.error(e.getMessage());
}
}

/** *//**
* Commit the database transaction.
* @throws HibernateException
*/
public void commit()...{
if(transactions == null)
return;
// Would be written as a no-op in an EJB container with CMT
Transaction tx = (Transaction)transactions.get();
try...{
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) ...{
tx.commit();
}
else...{
if(tx!=null && log.isWarnEnabled())
log.warn("Trying to commit the uncommitable transaction, nothing to do.");
}
}catch (Exception e) ...{
// TODO: handle exception
log.error(e.getMessage());
}
if(tx!=null)
transactions.set(null);
}

/** *//**
* Rollback the database transaction.
* @throws HibernateException
*/
public void rollback()...{
if(transactions == null)
return;
Transaction tx = (Transaction)transactions.get();
try...{
transactions.set(null);
if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) ...{
tx.rollback();
}
else...{
if(tx!=null && log.isWarnEnabled())
log.warn("Trying to rollback the unrollbackable transaction, nothing to do.");
}
}catch (Exception e) ...{
// TODO: handle exception
log.error(e.getMessage());
}
}

/** *//**
* 释放所有Hibernate占用的资源
* @throws HibernateException
*/
public void destroy()...{
if(sessionFactory!=null)...{
try...{
sessionFactory.close();
}catch (Exception e) ...{
// TODO: handle exception
log.error(e.getMessage());
}
sessionFactory = null;
}
sessions = null;
transactions = null;
if(log.isWarnEnabled())
log.warn("Hibernate("+hibernate_cfg+") was destroy successfully, all of sessions were closed.");
}
private URL hibernate_cfg;
SessionFactory sessionFactory;
ThreadLocal sessions;
ThreadLocal transactions;
private final static Log log = LogFactory.getLog(Hibernate.class);
}//对Hibernate操作接口的封装
package com.redsaga.quickstart.util;
import java.net.URL;
import net.sf.hibernate.Session;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.redsaga.quickstart.db.Hibernate;

/** *//**
* 对Hibernate操作接口的封装
* @author loemkie
*
*/
public class HibernateUtils...{
/** *//**
* Initialize the hibernate environment
* @param context
* @throws MalformedURLException
*/
public synchronized final static void init()...{
//Nothing to do
}

/** *//**
* 释放所有Hibernate占用的资源 */
public synchronized final static void destroy()...{
if(hibernate != null)
hibernate.destroy();
}

public final static Session getSession() ...{
if(hibernate != null)
return hibernate.getSession();
return null;
}

public final static void beginTransaction() ...{
if(hibernate != null)
hibernate.beginTransaction();
}

public final static void closeSession() ...{
if(hibernate != null)
hibernate.closeSession();
}

public final static void commit() ...{
if(hibernate != null)
hibernate.commit();
}

public final static void rollback() ...{
if(hibernate != null)
hibernate.rollback();
}
private final static String HIBERNATE_CFG = "/hibernate.cfg.xml";
private static Hibernate hibernate;
private final static Log log = LogFactory.getLog(HibernateUtils.class);
static...{
try...{
URL xml = HibernateUtils.class.getResource(HIBERNATE_CFG);
hibernate = Hibernate.init(xml);
}catch(Exception e)...{
log.fatal("Hibernate Initialize failed.", e);
}
}
}有了以上两个类,我们就可以很方便的使用hibernate,关于hibernate3的封装,有需要的给我email,接下来教大家怎么使用
先定义个session,
Session session = null;我们可以在程序初始化的时候调用下面的代码来获得session
好不容易写到这里,csdn的页面的插入代码不能用了,手工插入吧
session=HibernateUtils.getSession();
session就可以使用了
然后在程序结束的时候执行
HibernateUtils.closeSession();
笔者第一次写这类型的文章,希望大家多多支持,用了我的代码的人发表下感言,看过的也随便留下你的足迹,有回必访.
整整花了两个小时的时候来写这篇文章....
发表于 @ 2007年12月15日 21:14:00 | 评论( loading... ) | 举报| 收藏