Hibernate 是一个开放源代码的对象关系映射框架,它对JDBC进行了封装,提供了强大、高性能的对象关系型数据库的持久化服务。
主要步骤:
1.引入相关架包
以3.3.2 版本的Hibernate为例,首先下载hibernate-distribution-3.3.2.GA-dist.Zip文件。需要用到根目录下的hibernate3.jar、及lib\required 目录下所有的jar.
使用log4j 记录日志 需要log4j-1.2.16.jar 文件 另外还需要下载slf4j-1.5.8.zip 文件 需要其中的slf4j-log4j12-1.5.8.jar。
要连接Oracle 数据库还需要 ojdbc14.jar包,这个包可以在oracle 数据库的安装目录lib下找到.
2.添加可持久化类
即 对象的封装类。例:
private String pictureName;
private String pictureLink;
private Integer porder;
public Picture() {
}
public Picture(String pictureName, String pictureLink, Integer porder) {
this.pictureName = pictureName;
this.pictureLink = pictureLink;
this.porder = porder;
}
return this.id;
}
this.id = id;
}
return this.pictureName;
}
this.pictureName = pictureName;
}
return this.pictureLink;
}
this.pictureLink = pictureLink;
}
return this.porder;
}
this.porder = porder;
}
3.添加对象和关系型数据库表的映射文件(*.hbm.xml)
例:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="cn.com.hunter.entities.Picture" table="picture" catalog="test">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="pictureName" type="java.lang.String">
<column name="pictureName" length="50">
<comment>图片名称</comment>
</column>
</property>
<property name="pictureLink" type="java.lang.String">
<column name="pictureLink" length="50">
<comment>图片路径</comment>
</column>
</property>
<property name="porder" type="java.lang.Integer">
<column name="POrder">
<comment>排序</comment>
</column>
</property>
</class>
</hibernate-mapping>
4.添加LoginDao 类实现。(读取并解析配置文件、读取并解析映射信息,创建SessionFactory、打开Session、开始一个事务、用session.save 进行持久化操作、commit()提交事务、关闭session)代码如下;
public class LoginDao {
private Session session = null;
private Transaction tran =null;
public LoginDao(){
Configuration config = new Configuration().configure();
SessionFactory factory = config.buildSessionFactory();
this.session= factory.openSession();
}
public void save (Login login){
try{
tran = this.session.beginTransaction();
this.session.save(login);
tran.commit();
}catch (RuntimeException e) {
if(null!=tran){
tran.rollback();
}
throw e;
}finally{
this.session.close();
}
}
}
5..Hibernate配置文件(hibernate.cfg.xml 里面存放的主要是 数据库url 、数据库用户名、密码、JDBC驱动类信息)或hibernate.properties文件
需要在huberante.cfg.xml 文件里<session-factory>结束标签之前加:
<mapping resource = "com/test/Login.hbm.xml"/>