所使用的Jar包:
Hibernate:
Spring(使用MyEclipse自动导入框架功能)
Struts2:
注解包和MySql驱动包:
1、配置Hibernate和Spring:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="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/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"> <context:annotation-config /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="" /> <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> <property name="initialSize" value="1" /> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxActive" value="500" /> <!--最大空闲值,当经过一段峰值以后,连接会被释放掉一部分,直到释放到maxidle --> <property name="maxIdle" value="2" /> <!--最小空闲值 当空闲的连接数小于阀值时,连接池会主去的去申请一些连接 --> <property name="minIdle" value="1" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" > <property name="dataSource" ref="dataSource" /> <property name="mappingResources"> <list> <value>cn/raffaello/hbm/Person.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=false </value> </property> </bean> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="txManager"/> <bean id="personIDao" class="cn.raffaello.dao.impl.PersonDaoImpl" /> <bean id="personIService" class="cn.raffaello.service.impl.PersonServiceImpl"> <property name="personIDao" ref="personIDao" /> </bean> </beans>
2、新建实体和映射文件:
public class Person { public Person(){} public Person(String name) { super(); this.name = name; } private Integer id; private String name; 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; } }
<hibernate-mapping package="cn.raffaello.model"> <class name="Person" table="PERSON"> <id name="id" column="ID"> <generator class="native" /> </id> <property name="name" column="NAME" /> </class> </hibernate-mapping>
3、新建DaoBean,并在Bean中实现部分方法,使用@Resource给SessionFactory注入:
public interface PersonIDao { void add(Person person); void update(Person person); Person getById(Integer id); List<Person> getPersons(); }
public class PersonDaoImpl implements PersonIDao { @Resource(name="sessionFactory") private SessionFactory sessionFactory; @Override public void add(Person person) { sessionFactory.getCurrentSession().persist(person); } @Override public void update(Person person) { sessionFactory.getCurrentSession().merge(person); } @Override public Person getById(Integer id) { return (Person)sessionFactory.getCurrentSession().get(Person.class, id); } @SuppressWarnings("unchecked") @Override public List<Person> getPersons() { return sessionFactory.getCurrentSession().createQuery("from Person").list(); } }
5、新建ServiceBean,并实现部分方法;在ServiceBean的头部添加@Transactional 注解,使用该ServiceBean纳入Spring事务管理;
public interface PersonIService { void add(Person person); void update(Person person); Person getById(Integer id); List<Person> getPersons(); }
@Transactional public class PersonServiceImpl implements PersonIService { private PersonIDao personIDao; @Override public void add(Person person) { personIDao.add(person); } @Override public void update(Person person) { personIDao.update(person); } @Transactional(readOnly=true) @Override public Person getById(Integer id) { return personIDao.getById(id); } @Transactional(readOnly=true) @Override public List<Person> getPersons() { return personIDao.getPersons(); } public PersonIDao getPersonIDao() { return personIDao; } public void setPersonIDao(PersonIDao personIDao) { this.personIDao = personIDao; } }
6、测试Spring和Hibernate的代码:
public class test { private static PersonIService personIService; @BeforeClass public static void init(){ ApplicationContext cxt=new ClassPathXmlApplicationContext("beans.xml"); personIService=(PersonIService)cxt.getBean("personIService"); } @Test public void test() { personIService.add(new Person("克露丝")); personIService.add(new Person("Json")); personIService.add(new Person("布尔曼")); personIService.add(new Person("HHH")); personIService.add(new Person("汤姆")); } @Test public void testUpdate(){ Person person=personIService.getById(1); person.setName("汉克丝 hankesi"); personIService.update(person); } @Test public void testList(){ List<Person> list=personIService.getPersons(); for(Person per : list){ System.out.println(per.getName()); } } }
7、整合Struts2+Spring+Hibernate,将下面代码添加到Web.xml中:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
8、在Struts.xml中 进行如下配置:
<constant name="struts.118n.encoding" value="UTF-8" /> <!-- Action 后缀 --> <constant name="struts.action.extension" value="do,action" /> <!-- 设置浏览器是否缓存静态内容,默认值为true,开发环境下建议设置为false --> <constant name="struts.serve.static.browserCache" value="false" /> <!-- 当Struts 修改文件以后,是否重新加载该文件,默认为false,推荐开发环境下设置为true --> <constant name="struts.configuration.xml.reload" value="true" /> <!-- 开发模式下可以打印更详细的错误信息 --> <constant name="struts.devMode" value="false" /> <!-- 默认视图主题 --> <constant name="struts.ui.theme" value="simple" /> <!-- 与Spring集成是,指定有Spring创建Action对象 --> <constant name="struts.objectFactory" value="spring" /> <package name="raffaello" namespace="/raffaello" extends="struts-default"> <action name="main_*" class="cn.raffaello.action.MainAction" method="{1}"> <result name="message">/WEB-INF/pages/message.jsp</result> <result name="list">/WEB-INF/pages/list.jsp</result> </action> </package>
9、新建Action:MainAction:
public class MainAction { private String message; private Person person; private PersonIService personIService; public String hello(){ setMessage("struts2 测试消息!"); return "message"; } public String save(){ if(person!=null && !person.getName().equals("")){ personIService.add(person); setMessage("添加成功"); }else{ setMessage("对象为空"); } return "message"; } public String list(){ List<Person> list=personIService.getPersons(); HttpServletRequest request=ServletActionContext.getRequest(); request.setAttribute("PersonList", list); return "list"; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public PersonIService getPersonIService() { return personIService; } public void setPersonIService(PersonIService personIService) { this.personIService = personIService; } }10、添加测试代码和获取的测试代码:
<form action="/SSH2/raffaello/main_save.do" method="post"> 添加人员 <a target="_blank" href="/SSH2/raffaello/main_list.do">人员列表</a> <hr /> 姓名:<input type="text" name="person.name" /> <input type="submit" value="提交"> </form>
<span style="white-space:pre"> </span><c:forEach items="${PersonList}" var="per"> ${per.name} </c:forEach>