上篇博文中写了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 +后缀 -->
<bean
class="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容器中包含beanName
if(sc.context.containsBean(beanName)){
bean=sc.context.getBean(beanName);
}
//如果spring容器中不包含beanName
if(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的整合,就是这样。