该类只演示了如何增加一个Student,HibernateTemplate还封装了很多有用的方法,请查阅spring文档。 StudentManager中的sessionFactory是由spring注入的,但是StudentManager并没有对 sessionFactory做任何的处理,这是因为所有的处理都被HibernateDaoSupport.getHibernateTemplate ()封装。整个StudentManager中也看不到任何的异常处理,他们也都被基类封装了。
最后一个步骤就是在spring中注册StudentManger,然后向它注入sessionFactory:
- <bean id="studentManager" class="net.bromon.spring.examer.student.StudentManager">
- <property name="sessionFactory">
- <ref bean="sessionFactory"/>
- </property>
- </bean>
所有的配置都完成了,下面做单元测试:
- /*
- * 创建日期 2005-3-17
- */
- package net.bromon.spring.examer.student.test;
-
- import java.io.FileInputStream;
-
- import org.springframework.beans.factory.xml.XmlBeanFactory;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- import net.bromon.spring.examer.pojo.Student;
- import net.bromon.spring.examer.student.StudentManager;
- import junit.framework.TestCase;
-
- /**
- * @author Bromon
- */
- public class TestStudentManager extends TestCase {
-
- public void testAdd()
- {
- try
- {
- ApplicationContext context =new ClassPathXmlApplicationContext("springConfig.xml");
-
- Student s=new Student();
- s.setName("bromon");
- s.setPassword("123");
- s.setGrade(3);
- s.setSex(true);
-
- ((StudentManager)context.getBean("studentManager")).add(s);
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- }
-
- }
Spring已经将hibernate的操作简化到了非常高的程度,最关键的是整个开发可以由设计来驱动,如果一个团队对spring有足够的熟悉,那么完全可以由设计师规划所有的类,整理清楚类之间的关系,写成配置文件,然后编写hibernate映射文件,将数据表与pojo关联,成员就可以完全在设计方案内工作,利用spring封装好的hibernate模版,开发起来速度非常快,调试也很容易。它能够解决如何在团队内贯彻设计方案的问题。
由于本文不讲解hibernate的使用,所以相关内容请查阅hibernate文档。