spring+springmvc+hibernate整合執行個體,springmvchibernate
上篇博文中寫了spring與springmvc的整合,而這一篇則是又加上了hibernate。
與上次一樣,這一次仍然是先匯入jar包,這一次則要加入hibernate中的jar包,如所示:
同時再建立兩個源檔案夾,一個為config,一個為test,分別存放設定檔與測試案例,現在來進行spring,springmvc以及hibernate的配置。
建立spring-hibernate.xml,applicationContext.xml,springmvc.xml,hibernate.cfg.xml四個設定檔,現在來對這四個設定檔進行配置。
spring-hibernate.xml:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">]><beans> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"></property><property name="url" value="jdbc:mysql://localhost:3306/contacts"></property><property name="username" value="root"/><property name="password" value="root"/></bean><bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><prop key="show_sql">true</prop><prop key="hibernate.show_sql">true</prop> <prop key="hiberante.format_sql">true</prop></props></property> <property name="configLocations"><list><value>classpath:hibernate.cfg.xml</value></list></property><!-- 註解掃描的包 --> <!-- <property name="annotatedClasses"> <list> <value></value> </list> </property> --></bean><bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><bean id="transactionBese" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true" lazy-init="true"><property name="transactionManager" ref="transactionManager"></property><property name="transactionAttributes"><props><prop key="save*">PROPAGATION_REQUIRED,-Exception</prop><prop key="update*">PROPAGATION_REQUIRED,-Exception</prop><prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop></props></property></bean><bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"><property name="sessionFactory"><ref bean="sessionFactory"></ref></property></bean></beans>
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">]><beans><import resource="spring-hibernate.xml"></import><bean id="userDao" class="cn.com.dao.impl.UserDaoImpl"><property name="hibernateTemplate" ref="hibernateTemplate"></property></bean><bean id="userService" class="cn.com.service.impl.UserServiceImpl"><property name="userDao" ref="userDao"></property></bean></beans>
springmvc.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:mvc="http://www.springframework.org/schema/mvc"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/mvc http://www.springframework.org/schema/mvc/spring-mvc-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-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "><!-- mvc的註解驅動 --><mvc:annotation-driven /><!-- 一旦有掃描器的定義mvc:annotation-driven不需要,掃描器已經有了註解驅動的功能 --><context:component-scan base-package="cn.com.controller" /><!-- 首碼+ viewName +尾碼 --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- webroot到某一指定的檔案夾的路徑 --><property name="prefix" value="/WEB-INF/jsps/"></property><!-- 視圖名稱的尾碼 --><property name="suffix" value=".jsp"></property></bean><!-- id="multipartResolver"必須是multipartResolver --><bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- maxUploadSize:檔案上傳的最大值以byte為單位 --><property name="maxUploadSize" value="1024000"></property></bean></beans>
hibernate對應檔為:
<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><mapping resource="cn/com/domain/Users.hbm.xml"></mapping></session-factory></hibernate-configuration>
現在在web.xml中進行配置:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置spring啟動listener入口 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 配置springmvc啟動dispatcherServlet入口 --><!-- 中央控制器 --><servlet><servlet-name>springMVC</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><!-- encoding filter for jsp page --><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping> <servlet-mapping><servlet-name>springMVC</servlet-name><!-- struts習慣使用/*,在springmvc不管用 --><url-pattern>/</url-pattern></servlet-mapping></web-app>
現在開始編程過程:
User類:
package cn.com.domain;import java.io.Serializable;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;import org.hibernate.annotations.GenericGenerator;public class Users implements Serializable {private String id;private String name;private String pwd;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}}對應的User.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="cn.com.domain.Users" table="users"><id name="id" type="java.lang.String"><column name="id"></column></id><property name="name" type="java.lang.String" length="20"></property><property name="pwd" type="java.lang.String" length="20"></property></class></hibernate-mapping>
IUserDao:
package cn.com.dao;import cn.com.domain.Users;public interface IUserDao {public void addUser(Users user);public void updateUser(Users user);}IUserDaoImpl:
package cn.com.dao.impl;import org.springframework.orm.hibernate3.HibernateTemplate;import cn.com.dao.IUserDao;import cn.com.domain.Users;public class UserDaoImpl implements IUserDao {private HibernateTemplate hibernateTemplate;public HibernateTemplate getHibernateTemplate() {return hibernateTemplate;}public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {this.hibernateTemplate = hibernateTemplate;}public void addUser(Users user) {this.hibernateTemplate.save(user);}public void updateUser(Users user) {this.hibernateTemplate.update(user);}}IUserService:
package cn.com.service;import cn.com.domain.Users;public interface IUserService {public void addUser(Users users);public void updateUser(Users user);}IUserServiceImpl:
package cn.com.service.impl;import cn.com.dao.IUserDao;import cn.com.domain.Users;import cn.com.service.IUserService;public class UserServiceImpl implements IUserService {private IUserDao userDao;public void addUser(Users users) {this.userDao.addUser(users);}public IUserDao getUserDao() {return userDao;}public void setUserDao(IUserDao userDao) {this.userDao = userDao;}public void updateUser(Users user) {this.userDao.updateUser(user);}}編寫的一個工具類:
ServiceProvinderCore:
package cn.com.container;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * 該類的主要目的是載入spring設定檔 * @author Administrator * */public class ServiceProvinderCore {protected ApplicationContext context;public void load(String filename){context=new ClassPathXmlApplicationContext(filename);}}
ServiceProvinder:
package cn.com.container;import org.springframework.util.StringUtils;public class ServiceProvinder {private static ServiceProvinderCore sc;static{sc=new ServiceProvinderCore();sc.load("applicationContext.xml");}public static Object getService(String beanName){Object bean=null;if(!StringUtils.hasText(beanName)){throw new RuntimeException("您要訪問的服務名不可為空!");}//如果spring容器中包含beanNameif(sc.context.containsBean(beanName)){bean=sc.context.getBean(beanName);}//如果spring容器中不包含beanNameif(bean==null){throw new RuntimeException("您要訪問的服務名稱["+beanName+"]不存在");}return bean;}}控制器UserController:
package cn.com.controller;import java.util.UUID;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import cn.com.container.ServiceProvinder;import cn.com.dao.IUserDao;import cn.com.domain.Users;import cn.com.service.IUserService;@Controller@RequestMapping("/user")public class UserController {@RequestMapping("/toSuccess.do")public String toSuccess(){System.out.println("success");return "success";}@RequestMapping("/toAdd.do")public String add(){return "add";}@RequestMapping("/toLogin.do")public String login(){return "login";}@RequestMapping("/toSave.do")public String save(Users user){System.out.println(user.getName());System.out.println(user.getPwd());String id=UUID.randomUUID().toString().replace("-", "").substring(0,4);user.setId(id);ServiceProvinder provinder=new ServiceProvinder();IUserService userDao=(IUserService) provinder.getService("userService");userDao.addUser(user);return "success";}}在這些包以及各個類的編寫中,總體結構為:
現在來進行測試:
add.jsp
點擊提交以後:
jsp頁面轉向為:
成功完成整合。
在這裡使用的是xml配置的檔案來進行開發,如果是使用註解來做的話會更為簡單一些。
spring+springmvc+hibernate的整合,就是這樣。