1..首先引入相关包:
Spring相关包+Struts相关包+Hibernate相关包
2.配置好Spring的beanx.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" > <context:annotation-config></context:annotation-config> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8"></property> <property name="username" value="root"></property> <property name="password" value="123"></property> <!-- 连接池启东时的初始值 --> <property name="initialSize" value="1"></property> <!-- 连接池的最大值 --> <property name="maxActive" value="500"></property> <!-- 最大空闲值 --> <property name="maxIdle" value="2"></property> <!-- 最小空闲值 --> <property name="minIdle" value="1"></property> </bean> <!-- 配置Hibernate --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mappingResources"> <list> <value>cn/itcast/bean/Person.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=update hibernate.show_sql=false hibernate.format_sql=false <!-- 解决问题是加入了二级缓存的配置 --> hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=false hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider </value> </property> </bean> <!-- 事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 注释驱动 --> <tx:annotation-driven transaction-manager="txManager"/> <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"/> </beans> <!-- 必须联网才能够读取文件 -->
package cn.itcast.bean; public class Person { private Integer id; private String name; public Person(){} public Person(String name) { this.name = 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; } }
4.编写与Person类与数据库itcast中表person相对应的映射
Person.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 package="cn.itcast.bean"> <class name="Person" table="person"> <cache usage="read-write" region="cn.itcast.bean.Person"/> <id name="id"> <generator class="native"></generator> </id> <property name="name" length="10" not-null="true"></property> </class> </hibernate-mapping>
package cn.itcast.service; import java.util.List; import cn.itcast.bean.Person; public interface PersonService { public void save(Person person); public void update(Person person); public void delete(Integer personid); public Person getPerson(Integer personid); public List<Person> getPersons(); }
package cn.itcast.service.impl; import java.util.List; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import cn.itcast.bean.Person; import cn.itcast.service.PersonService; @Transactional public class PersonServiceBean implements PersonService { @Resource private SessionFactory sessionFactory; public void save(Person person){ sessionFactory.getCurrentSession().persist(person); } public void update(Person person){ sessionFactory.getCurrentSession().merge(person); } public void delete(Integer personid){ sessionFactory.getCurrentSession().delete( sessionFactory.getCurrentSession().load(Person.class, personid)); } @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public Person getPerson(Integer personid){ return (Person)sessionFactory.getCurrentSession().get(Person.class, personid); } @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) @SuppressWarnings("unchecked") public List<Person> getPersons(){ return sessionFactory.getCurrentSession().createQuery("from Person").list(); } }
junit.test包写的PersonServiceTest类:
package junit.test; import static org.junit.Assert.fail; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.bean.Person; import cn.itcast.service.PersonService; public class PersonServiceTest { private static PersonService personService; @BeforeClass public static void setUpBeforeClass() throws Exception { try { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); personService = (PersonService) applicationContext.getBean("personService"); } catch (Exception e) { e.printStackTrace(); } } @Test public void testSave() { personService.save(new Person("小张")); } @Test public void testUpdate() { Person person = personService.getPerson(1); person.setName("张三"); personService.update(person); } @Test public void testDelete() { personService.delete(1); } @Test public void testGetPerson() { System.out.println(personService.getPerson(1).getName()); } @Test public void testGetPersons() { for(Person person:personService.getPersons()){ System.out.println(person.getName()); } } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <action-mappings> <action path="/person/list" type="cn.itcast.web.action.PersonAction" validate="false"> <forward name="list" path="/WEB-INF/page/personlist.jsp"></forward> </action> </action-mappings> </struts-config>
PersonAction类:
package cn.itcast.web.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import cn.itcast.service.PersonService; public class PersonAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext()); PersonService personService = (PersonService) ctx.getBean("personService"); request.setAttribute("persons", personService.getPersons()); return mapping.findForward("list"); } }
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <!-- 对Spring容器进行实例化 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>struts</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>struts</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
编写V:
在WEB-INF/page/personlist.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>人员列表</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <c:forEach items="${persons }" var="person"> ID=${person.id },Name=${person.name }<br> </c:forEach> </body> </html>