springMVC系列之与spring3.2 , hibernate4.1.6整合——08

springMVC系列之与spring3.2 , hibernate4.1.6整合——08


摘要: 本文主要讲述整合springMVC, spring, hibernate的具体过程, 并连接上oracle进行简单的DUAL.


一: 实现功能


        1、springMVC、spring、hibernate整合过程

        2、实现简单的DUAL


二:具体步骤


        1、springMVC、spring、hibernate整合过程

                a)       引入jar包、具体jar包如下图:


                            springMVC系列之与spring3.2 , hibernate4.1.6整合——08_第1张图片


                b)       使用spring的bean配置关于连接数据库的一些信息、hibernate的常用配置信息、及事务的管理方式springAnnotation-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="oracle.jdbc.driver.OracleDriver" />
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:chen" />
		<property name="username" value="chen" />
		<property name="password" value="chen" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 为sessionFactory注入dataSource -->
		<property name="dataSource" ref="dataSource" />
		<!-- 常用hibernate配置 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hiberante.format_sql">true</prop>
			</props>
		</property>
		<!-- 加载用于生成数据库中表的hibernate配置文件。 -->
		<property name="configLocations">
			<list>
				<value>
					classpath*:com/chy/ssh/web/annotation/hibernate/hibernate.cfg.test.xml
				</value>
			</list>
		</property>
	</bean>

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- 事务管理 、当使用spring为每个Controller注入属性时引用此bean、为其添加事务管理 -->
	<bean id="transactionBese"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
		lazy-init="true" abstract="true">
		<property name="transactionManager" ref="transactionManager"></property>
		<!-- 根据不同的操作开启不同的事务管理方式 -->
		<property name="transactionAttributes">
			<props>
				<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
				<prop key="get*">PROPAGATION_NEVER</prop>
			</props>
		</property>
	</bean>
</beans>

                c)       配置hibernate的配置文件、用于生成表。这里不是通过写每一个实体类的hibernate.hbm.xml来对应数据库中的table、而是通过注解的方式来实现的。                                           hibernate.cfg.test.xml:


<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
    	<!-- 用于关联表的实体类 -->
        <mapping class="com.chy.ssh.web.annotation.entity.User"/>
    </session-factory>
</hibernate-configuration>

                        具体的entity——User:


package com.chy.ssh.web.annotation.entity;

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;

@Entity
@Table(name="T_USER")
public class User {

	@Id
	@GeneratedValue(generator="system-uuid")
	@GenericGenerator(name="system-uuid", strategy="uuid")
	@Column(length=32)
	private String id;
	
	@Column(length=32)
	private String userName;
	
	@Column(length=32)
	private int age;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}	
}

                d)       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">

	<!-- 加载配置文件、这里在classpath下写多个不同的文件是为了在团体开发中、不同的小组有不同的配置文件、 这样就不会相互影响、减小冲突、易于管理、最后在主要的配置文件中导入各个模块的配置文件即可! -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:config/springAnnotation-*.xml</param-value>
	</context-param>


	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<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*:config/springAnnotation-servlet.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>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- 用于session的管理、解决事务提交后再次操作数据库不能正常打开session的问题 -->
	<filter>
		<filter-name>openSession</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>openSession</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

        2、实现简单的DUAL:没有多少要说的地方、主要介绍两个类:UserDAOImpl、UserController、具体的代码中都有说明

                a)       UserDAOImpl:


package com.chy.ssh.web.annotation.dao;

import java.util.List;


import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.chy.ssh.web.annotation.entity.User;

public class UserDAOImple implements UserDAO {
	
	private SessionFactory sessionFactory;
	
	public void addUser(User user) {
		sessionFactory.getCurrentSession().save(user);
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	public List<User> getAllUser() {
		String hql = "from User";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return query.list();
	}

	public boolean delUser(String userId) {
		String hql = "delete from User u where u.id=?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, userId);
		return (query.executeUpdate() > 0);
	}
	
	public User getUser(String id) {
		String hql = "from User u where u.id=?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, id);
		
		return (User) query.uniqueResult();
	}

	public boolean updateUser(User user) {
		String hql = "update User u set u.userName=?,u.age=? where u.id=?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, user.getUserName());
		query.setInteger(1, user.getAge());
		query.setString(2, user.getId());		
		return (query.executeUpdate() > 0);
	}
}

                b)       UserController:


package com.chy.ssh.web.annotation.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chy.ssh.web.annotation.entity.User;
import com.chy.ssh.web.annotation.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource(name="userManager")
	private UserService userManager;
	
	@RequestMapping("/toUser")
	public String toUser(){
		return "/addUser";
	}
	
	@RequestMapping("/addUser")
	public String addUser(@ModelAttribute("pojo")User user){
		userManager.addUser(user);
		return "/success";
	}
	
	@RequestMapping("/getAllUser")
	public String getAllUser(HttpServletRequest request){
		List<User> userList = userManager.getAllUser();
		request.setAttribute("userList", userList);
		return "/userManager";
	}
	
	@RequestMapping("/delUser")
	public void delUser(String id,HttpServletResponse response){
		String result = "{\"result\":\"error\"}";
		if(userManager.delUser(id)){
			result = "{\"result\":\"success\"}";
		}
		PrintWriter out = null;
		response.setContentType("application/json");
		try {
			out = response.getWriter();
			out.write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/getUser")
	public String getUser(String id,HttpServletRequest request){
		User user = userManager.getUser(id);
		request.setAttribute("user", user);
		return "/editUser";
	}
	
	@RequestMapping("/updateUser")
	public String updateUser(User user,HttpServletRequest request){
		if(userManager.updateUser(user)){
			user = userManager.getUser(user.getId());
			request.setAttribute("user", user);
			return "/editUser";
		}else{
			return "/error";
		}
	}
}

补充:

1、整体结构图:


                                  springMVC系列之与spring3.2 , hibernate4.1.6整合——08_第2张图片


2、第一次访问URL:http://localhost:8080/springMVC_spring_hibernate/user/toUser

3、addUser.jsp:


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
</script>
</head>
<body>
	<h3>添加用户</h3>
	<form action="/springMVC_spring_hibernate/user/addUser" method="post">
		姓名:<input type="text" name="userName">
		年龄:<input type="text" name="age">
		<input type="submit" value="添加">
	</form>
</body>
</html>

4、success.jsp:


<body>
	springMVC + spring + hibernate 集成成功!!!
</body>

5、访问获取所有学生信息URL:http://localhost:8080/springMVC_spring_hibernate/user/getAllUser

6、userManager.jsp:


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户管理</title>
<script type="text/javascript">
	function del(id) {
		alert(id);
		$.get("/springMVC_spring_hibernate/user/delUser?id=" + id, function(
				data) {
			alert(data.result);
			if ("success" == data.result) {
				alert("删除成功!");
				window.location.reload();
			} else {
				alert("删除失败!");
			}
		});
	}
</script>
</head>
<body>

	<table border="1">
		<tbody>
			<tr>
				<th>姓名</th>
				<th>年龄</th>
				<th>编辑</th>
			</tr>
			<c:if test="${!empty userList }">
				<c:forEach items="${userList }" var="u">
					<tr>
						<td>${u.userName }</td>
						<td>${u.age }</td>
						<td>
							<a href="/springMVC_spring_hibernate/user/getUser?id=${u.id }">编辑</a>
							<a href="javascript:del('${u.id }')">删除</a>
							</td>
					</tr>
				</c:forEach>
			</c:if>
		</tbody>
	</table>
</body>
</html>

7、editUser.jsp:


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改用户</title>
</head>
<body>
	<h3>修改用户</h3>
	<form name="userForm" action="/springMVC_spring_hibernate/user/updateUser" method="post">
		<input type="hidden" name="id" value="${user.id }">
		姓名:<input type="text" name="userName" value="${user.userName }">
		年龄:<input type="text" name="age" value="${user.age }">
		<input type="submit" value="编辑" >
	</form>
</body>
</html>

更多内容: springMVC系列之目录——00



你可能感兴趣的:(spring,Hibernate,ModelAndView)