1.引入jar包
(spring开发包,ojdbc.jar,dbcp连接池,hibernate框架开发包)
2.新建applicationContext-hibernate.xml
首先,配置好数据源dataSource,
其次,加入SessionFactory,
第三,配置映射文件
spring配置文件例子:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
<bean id="mydataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="oracle.jdbc.OracleDriver">
</property>
<property name="url"
value="jdbc:oracle:thin:@192.168.0.20:1521:tarena">
</property>
<property name="username" value="task">
</property>
<property name="password" value="mistarena">
</property>
<property name="initialSize" value="2">
</property>
<property name="maxActive" value="15">
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 注入dataSource连接资源 -->
<property name="dataSource"
ref="mydataSource">
</property>
<!-- 注入hibernate配置参数 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<!-- 注入hibernate映射描述文件 -->
<property name="mappingResources">
<list>
<value>tarena/entity/Fee.hbm.xml</value>
</list>
</property>
</bean>
</beans>
3.新建实体类
4.新建xxx.hbm.xml映射文件
5.新建dao接口
6.新建dao接口实现类,继承HibernateDaoSupport
7.修改spring配置文件,加入dao实现类的bean,
在bean中注入sessionFactory
例子:
<bean id="hibernateFeeDAO" class="tarena.dao.HibernateFeeDAO">
<property name="sessionFactory" ref="sessionFactory">
</property>
</bean>
8.dao实现类代码例子
public class HibernateFeeDAO extends HibernateDaoSupport implements FeeDAO{
public void delete(Fee fee) {
this.getHibernateTemplate().delete(fee);
}
public List<Fee> findAll() {
String hql = "from Fee";
List<Fee> list = this.getHibernateTemplate().find(hql);
return list;
}
public Fee findById(int id) {
Fee fee = (Fee)this.getHibernateTemplate().get(Fee.class, id);
return fee;
}
public void save(Fee fee) {
this.getHibernateTemplate().save(fee);
}
public void update(Fee fee) {
this.getHibernateTemplate().update(fee);
}
}