思路:将Hibernate做完映射之后的对象传给Spring来管理;
直接在applicationContext.xml进行配置:
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd">
<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 数据源dataSource用c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- sessionFactory的配置,并注入dataSource -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref bean="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
<!-- 加载entity类的配置文件-->
<property name="mappingResources">
<list>
<value>entity/Coupons.hbm.xml</value> <value>entity/Customerbase.hbm.xml</value>
<value>entity/Products.hbm.xml</value>
<value>entity/Users.hbm.xml</value>
<value>entity/Prize.hbm.xml</value>
<value>entity/Orders.hbm.xml</value>
</list>
</property>
</bean>
<!--将sessionFactory注入到DAO-->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.hibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</bean>
<!--将hibernateTemplate注入到DAO,HibernateTemplate类提供了一些dao操作的方法-->
<bean id="CouponsDAO" class="dao.CouponsDAO">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
</beans>
HibernateTemplate类提供了一些dao操作的常用方法:
get:从数据库相关表获取到一条记录并封装返回一个对象;
save:添加记录
saveOrUpdate:判断相应记录是否已存在,据此进行添加或者修改记录
update:修改记录
delete:删除记录
总结:但通过上面我们发现,我们的每一个dao都要在xml注入sessionFactory或者hibernateTemplate这种配置重复的工作的解决方法时我们可以自己抽出一个SuperDao类去配置,然后让我们的dao类直接去继承这个SuperDao类。