1.导入jar包
导入使用Hibernate所需要的Jar包,拷贝到项目的lib目录下
2.新建配置文件hibernate.cfg.xml
注意:应该放在源文件的src目录下,默认为hibernate.cfg.xml
例子:
<?xmlversion='1.0' encoding='UTF-8'?>
<!DOCTYPEhibernate-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>
<propertyname="dialect">
org.hibernate.dialect.OracleDialect
</property>
<propertyname="connection.url">
jdbc:oracle:thin:@192.168.0.20:1521:tarena
</property>
<propertyname="connection.username">task</property>
<propertyname="connection.password">mistarena</property>
<propertyname="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<!-- 将hibernate底层执行的sql语句从控制台显示 -->
<propertyname="show_sql">true</property>
<propertyname="format_sql">true</property>
</session-factory>
</hibernate-configuration>
hibernate.cfg.xml配置说明
3.新建POJO类表示普通类
POJO类表示普通类(Plain Ordinary Old Object),没有格式的类,只有属性和对应的getter/setter方法,而没有任何业务逻辑方法的类。
这种类最多再加入equals()、hashCode()、toString()等重写父类Object的方法。不承担任何实现业务逻辑的责任
4.新建映射文件Fee.hbm.xml
映射文件用于指明POJO类和表之间的映射关系(xx属性对应xx字段)
一个类对应一个映射文件。
注意:映射文件默认与POJO类放在一起;命名规则为类名.hbm.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.tarena.netctoss.pojo.Fee" table="COST"> <id name="id" column="ID" type="integer"> <generator class="sequence"> <param name="sequence">FEE_SEQ</param> </generator> </id> <property name="feeName" column="NAME" type="string"> </property> <property name="baseDuration" column="BASE_DURATION" type="integer"> </property> <property name="baseCost" column="BASE_COST" type="float"> </property> <property name="unitCost" column="UNIT_COST" type="float"> </property> <property name="status" column="STATUS" type="string"> </property> <property name="descr" column="DESCR" type="string"> </property> <property name="costType" column="COST_TYPE" type="string"> </property> <property name="createTime" column="CREATIME" type="date"> </property> <property name="startTime" column="STARTIME" type="date"> </property> </class> </hibernate-mapping>
主键一般都是自动生成的。我们一般不使用业务数据作为主键,因为业务逻辑的改变有可能会改变主键值。
生成主键方式可以有很多种,常用的包括assigned、foreign、identity、increment、native、sequence、uuid等。
主键生成方式是枚举类型,只能从一个有限的范围内选择,不能自定义。
5.在配置文件中关联映射文件
<mappingresource="com/pojo/Fee.hbm.xml"/>
6.新建HibernateUtil,用于封装创建Session的方法
例子:
package com.tarena.netctoss.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public classHibernateUtil{
private staticSessionFactorysf;
static{
Configurationconf= new Configuration();
//加载hibernate配置
conf.configure("/hibernate.cfg.xml");
//获取sessionFactory
sf = conf.buildSessionFactory();
}
public staticSessiongetSession(){
//获取session
Session session = sf.openSession();
return session;
}
}
如上,每个用户会对应一个Session,但是SessionFactory是共享的。
7.写dao测试
public classTestFeeDAO{
public staticvoidmain(String[] args){
// testSave();
testFindById();
// testFindAll();
// testDelete();
// testFindAll();
// testUpdate();
}
/**
* 测试更新
*/
public staticvoidtestUpdate(){
//如果更新部分字段,需要先查询再更新
//如果更新所有字段值,可以直接new并设置每个字段值
// fee.setId(1);
// fee.setFeeName("包月2");
// fee.setBaseDuration(200);
// fee.setBaseCost(400.0f);
// fee.setUnitCost(4.0f);
// fee.setStatus("0");
// fee.setDescr("资费描述1");
// fee.setCreateTime(new Date(System.currentTimeMillis()));
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Fee fee=(Fee)session.load(Fee.class,182);
fee.setStatus("1");
fee.setStartTime(newDate(System.currentTimeMillis()));
session.update(fee);//,开启资费,将fee对象更新到数据库
tx.commit();
session.close();
}
/**
* 测试删除
*/
public staticvoidtestDelete(){
Session session = HibernateUtil.getSession();
Fee fee=new Fee();
fee.setId(183);//可以new,也可以查询
Transaction tx = session.beginTransaction();
session.delete(fee);//按id作条件删除
tx.commit();
session.close();
}
/**
* 测试按主键当条件查询
*/
public staticvoidtestFindById(){
Session session = HibernateUtil.getSession();
Fee fee=(Fee)session.load(Fee.class,182);
System.out.println(fee);//get方法没有记录时返回null
System.out.println(fee.getId()+" "+fee.getFeeName());
System.out.println(fee.getBaseDuration()+" "+fee.getBaseCost());
session.close();
}
/**
* 测试查询所有资费记录
*/
public staticvoidtestFindAll(){
String hql = "from Fee";
Session session = HibernateUtil.getSession();
Query query = session.createQuery(hql);
List<Fee> list = query.list();
for(Feefee: list){
System.out.println(fee.getId()+" "+fee.getFeeName());
}
session.close();
}
/**
* 测试添加操作
*/
public staticvoidtestSave(){
Fee fee=new Fee();
// fee.setId(id);//hibernate负责管理,不用指定
fee.setFeeName("包月12");
fee.setBaseDuration(100);
fee.setBaseCost(200.0f);
fee.setUnitCost(2.0f);
fee.setStatus("0");
fee.setDescr("资费描述");
fee.setCostType("1");
fee.setCreateTime(newDate(System.currentTimeMillis()));
//借助于hibernate保存到数据库
Session session = HibernateUtil.getSession();
//打开事务
Transaction tx = session.beginTransaction();
//保存
session.save(fee);
//提交事务
tx.commit();
//释放
session.close();
}
}