1.1 问题
使用Spring整合Hibernate,并实现资费表的增、删、改、查。
1.2 方案
Spring整合Hibernate的步骤:
1.3 步骤
实现此案例需要按照如下步骤进行。
采用的环境是eclipse ,jdk 7.0 ,Tomcat7.0 ,Spring 3.2 ,Hibernate 3.2 。
创建WEB项目SpringHibernate,并导入数据库驱动包、Hibernate开发包以及Spring开发包,完成后项目中包结构如下图
然后,增加到类编译中。
引入Spring配置文件applicationContext.xml,放在src根路径下。在该文件中配置数据源、SessionFactory、开启组件扫描、声明式事务,代码如下
<?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="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- 配置连接参数 --> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/cnblogs"/> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="user" value="root"/> <property name="password" value="123456"/> <!-- 配置连接池 --> <property name="initialPoolSize" value="3"/> <property name="maxPoolSize" value="10"/> <property name="minPoolSize" value="1"/> <property name="acquireIncrement" value="3"/> <property name="maxIdleTime" value="60"/> </bean> <!-- 配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 依赖数据源 --> <property name="dataSource" ref="ds"/> <!-- Hibernate框架相关配置 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.formate_sql">true</prop> </props> </property> <property name="mappingResources"> <list> <value>com/souvc/entity/Cost.hbm.xml</value> </list> </property> </bean> <!-- 开启注解扫描 --> <context:component-scan base-package="com.souvc"/> <!-- 声明式事务管理,采用AOP形式切入 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="load*" read-only="true" /> <tx:method name="execute" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config proxy-target-class="true"> <aop:advisor advice-ref="txAdvice" pointcut="within(com.souvc.action.*)" /> </aop:config> </beans>
创建com.souvc.entity包,并在包下创建资费实体类和映射关系文件,其中实体类Cost代码如下
package com.souvc.entity; import java.util.Date; /** * 资费实体类 */ public class Cost { private Integer id;// 主键 private String name;// 资费名称 private Integer baseDuration;// 在线时长 private Double baseCost;// 基本费用 private Double unitCost;// 单位费用 private String status;// 状态 private String descr;// 资费说明 private Date createTime;// 创建日期 private Date startTime;// 启用日期 private String costType;// 资费类型 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getBaseDuration() { return baseDuration; } public void setBaseDuration(Integer baseDuration) { this.baseDuration = baseDuration; } public Double getBaseCost() { return baseCost; } public void setBaseCost(Double baseCost) { this.baseCost = baseCost; } public Double getUnitCost() { return unitCost; } public void setUnitCost(Double unitCost) { this.unitCost = unitCost; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDescr() { return descr; } public void setDescr(String descr) { this.descr = descr; } public Date getCreateTime() { return createTime; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCostType() { return costType; } public void setCostType(String costType) { this.costType = costType; } }
映射关系文件Cost.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.souvc.entity.Cost" table="cost"> <!-- 配置主键属性和字段的关系 --> <id name="id" type="java.lang.Integer" column="id"> <!-- 用来指明主键的生成方式 --> <!-- <generator class="sequence"> <param name="sequence">emp_seq</param> </generator> --> <generator class="native"> </generator> </id> <!-- 配置实体类中属性与表中字段的关系 --> <property name="name" type="string" column="name" /> <property name="baseDuration" type="integer" column="base_duration" /> <property name="baseCost" type="double" column="base_cost" /> <property name="unitCost" type="double" column="unit_cost" /> <property name="status" type="string" column="status" /> <property name="descr" type="string" column="descr" /> <property name="createTime" type="date" column="creatime" /> <property name="startTime" type="date" column="startime" /> <property name="costType" type="string" column="cost_type" /> </class> </hibernate-mapping>
在applicationContext.xml中注册映射关系文件,代码如下
<property name="mappingResources"> <list> <value>com/souvc/entity/Cost.hbm.xml</value> </list> </property>
创建包com.souvc.dao,并在包下创建资费DAO接口,声明增、删、改、查的方法,代码如下
package com.souvc.dao; import java.util.List; import com.souvc.entity.Cost; public interface ICostDao { List<Cost> findAll(); Cost findById(int id); void save(Cost cost); void update(Cost cost); void delete(int id); }
创建DAO实现类CostDaoImpl,继承于HibernateDaoSupport,实现接口ICostDao。代码如下
package com.souvc.dao; import java.util.List; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import com.souvc.entity.Cost; @SuppressWarnings("unchecked") @Repository public class CostDaoImpl extends HibernateDaoSupport implements ICostDao { @Resource public void setSF(SessionFactory sf) { super.setSessionFactory(sf); } @Override public List<Cost> findAll() { String hql = "from Cost"; return getHibernateTemplate().find(hql); } @Override public Cost findById(int id) { return (Cost) getHibernateTemplate().get(Cost.class, id); } @Override public void save(Cost cost) { getHibernateTemplate().save(cost); } @Override public void update(Cost cost) { getHibernateTemplate().update(cost); } @Override public void delete(int id) { Cost c = new Cost(); c.setId(id); getHibernateTemplate().delete(c); } }
在com.souvc.dao包下,创建JUNIT测试类TestDao,分别写出资费的增、删、改
查测试方法,并执行这些方法进行测试。代码如下
package com.souvc.dao; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.souvc.entity.Cost; /** * * 类名: TestDao * 描述: 测试类 * 开发人员: souvc * 创建时间: 2015-9-6 下午1:01:44 * 发布版本:V3.0 */ public class TestDao { private String conf = "applicationContext.xml"; /** * 方法名:test1 * 详述:查询所有 * 开发人员:souvc * 创建时间:2015-9-6 下午12:59:30 * 说明参数含义 * 说明返回值含义 * 说明发生此异常的条件 */ @Test public void test1() { ApplicationContext ctx = new ClassPathXmlApplicationContext(conf); ICostDao dao = (ICostDao) ctx.getBean("costDaoImpl"); List<Cost> list = dao.findAll(); for (Cost c : list) { System.out.println(c.getId() + " " + c.getName()); } } /** * 方法名:test2 * 详述:通过id查询 * 开发人员:souvc * 创建时间:2015-9-6 下午1:00:07 * 说明参数含义 * 说明返回值含义 * 说明发生此异常的条件 */ @Test public void test2() { ApplicationContext ctx = new ClassPathXmlApplicationContext(conf); ICostDao dao = (ICostDao) ctx.getBean("costDaoImpl"); Cost c = dao.findById(1); System.out.println(c.getId() + " " + c.getName()); } /** * 方法名:test3 * 详述:新增 * 开发人员:souvc * 创建时间:2015-9-6 下午1:00:32 * 说明参数含义 * 说明返回值含义 * 说明发生此异常的条件 */ @Test public void test3() { ApplicationContext ctx = new ClassPathXmlApplicationContext(conf); ICostDao dao = (ICostDao) ctx.getBean("costDaoImpl"); Cost c = new Cost(); c.setName("aaa"); c.setBaseDuration(20); c.setBaseCost(2.0); c.setUnitCost(0.2); c.setCostType("1"); c.setStatus("0"); dao.save(c); } /** * 方法名:test4 * 详述:更新 * 开发人员:souvc * 创建时间:2015-9-6 下午1:00:59 * 说明参数含义 * 说明返回值含义 * 说明发生此异常的条件 */ @Test public void test4() { ApplicationContext ctx = new ClassPathXmlApplicationContext(conf); ICostDao dao = (ICostDao) ctx.getBean("costDaoImpl"); Cost c = dao.findById(1); c.setName("bbb"); dao.update(c); } /** * 方法名:test5 * 详述:删除 * 开发人员:liuhf * 创建时间:2015-9-6 下午1:01:19 * 说明参数含义 * 说明返回值含义 * 说明发生此异常的条件 */ @Test public void test5() { ApplicationContext ctx = new ClassPathXmlApplicationContext(conf); ICostDao dao = (ICostDao) ctx.getBean("costDaoImpl"); dao.delete(1); } }
建表语句:
CREATE TABLE `cost` ( `id` int(10) NOT NULL auto_increment, `name` varchar(50) default NULL, `base_duration` int(11) default NULL, `unit_cost` double(10,0) default NULL, `status` varchar(10) default NULL, `descr` varchar(20) default NULL, `creatime` date default NULL, `startime` date default NULL, `cost_type` varchar(10) default NULL, `base_cost` double(10,0) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
以上的源码如下:
http://yunpan.cn/cmvceCwSyjbXi 访问密码 3930