前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springmvc、spring、hibernate整合示例

springmvc、spring、hibernate整合示例

作者头像
yawn
发布2018-03-14 11:08:03
1.1K0
发布2018-03-14 11:08:03
举报

在mysql数据库中建立一个user表,已对user的增删改查为例,整合springmvc、spring、hibernate。

1.web.xml中的配置:①spring监听器;②spring mvc的servlet;③字符编码过滤器。

<!-- spring 监听器的配置 -->
<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>
  
<!-- springMVC 配置 -->
<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:user-servlet.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>springmvc</servlet-name>
	<url-pattern>*.do</url-pattern>
</servlet-mapping>

<!-- 字符编码过滤器 -->
<filter>
	<filter-name>characterEncodingFilter</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>
<filter-mapping>
	<filter-name>characterEncodingFilter</filter-name>
	<url-pattern>/* </url-pattern>
</filter-mapping>

2.spring mvc配置文件 user-servlet.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<!-- 	<context:component-scan base-package="com.yawn.controller"></context:component-scan>	 -->
	
 	<context:component-scan base-package="com.yawn.*" use-default-filters="false">
 		<context:include-filter type="annotation" 
 			expression="org.springframework.stereotype.Controller"/>
 	</context:component-scan>
	
	<mvc:annotation-driven/>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

</beans>

3.spring的配置文件beans.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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<context:component-scan base-package="com.yawn.*">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>


	<context:property-placeholder location="classpath:db.properties"/>
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 配置dataSource数据源 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 
			引入hibernate配置文件 
			<property name="configLocation" value="classpath:hibernate.cfg.xml" />
		-->
		<!-- 使用此配置就可以不再引入hibernate配置文件 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
<!-- 				<prop key="hibernate.mappings">com.yawm.entity.User</prop> -->
			</props>
		</property>
		<!-- 使用此配置代替以前hibernate中使用的mappingLocations配置 -->
 		<property name="annotatedClasses">
 			<list>
 				<value>com.yawn.entity.User</value>
 			</list>
 		</property>
	</bean>

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


	<tx:annotation-driven transaction-manager="transactionManager" />
	<aop:aspectj-autoproxy />

</beans>

3.1.db.properties数据库属性配置文件:

######################################
##	configuration of database		##
######################################

jdbc.jdbcUrl=jdbc\:mysql\://localhost\:3306/volunteer?useUnicode\=true&characterEncoding\=utf8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
jdbc.initialPoolSize=20
jdbc.maxPoolSize=50

4.controller的设计:

package com.yawn.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yawn.entity.User;
import com.yawn.service.UserService;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;

	public UserController() {
	}
	
	@RequestMapping("getAll")
	private List<User> getAll() {
		return userService.getAll();
	}
	
	@RequestMapping(value="updateUser/{id}", method={RequestMethod.GET})
	private String updateUser(@PathVariable int id, Map<String,User> map){
		
		map.put("user", userService.getUserById(id));
		
		return "updateUser";
	}
	
	@RequestMapping(value="updateUser", method={RequestMethod.POST})
	private String updateUser(User user){
		
		userService.updateUser(user);
		
		return "redirect:getAll.do";
	}
	
	@RequestMapping(value="deleteUser/{id}", method={RequestMethod.GET})
	private String deleteUser(@PathVariable int id){
		
		userService.deleteUser(id);
		
		return "redirect:/getAll.do";
	}
	
	@RequestMapping(value="addUser", method={RequestMethod.GET})
	private void addUser(){
		// 或者使用静态资源都可以跳转到addUser.jsp页面
	}
	@RequestMapping(value="addUser", method={RequestMethod.POST})
	private String addUser(User user, BindingResult result){
		
		System.out.println(result);
		
		userService.addUser(user);
		
		return "redirect:/getAll.do";
	}
	
}

5.service的设计:

package com.yawn.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yawn.dao.UserDao;
import com.yawn.entity.User;

@Service
public class UserService {
	
	@Autowired
	private UserDao userDao;

	public UserService() {
	}
	
	public List<User> getAll(){
		
		return userDao.getAll();
	}
	
	public boolean updateUser(User user){
		return userDao.updateUser(user);
	}
	
	public User getUserById(int id){
		return userDao.getUserById(id);
	}
	
	public boolean deleteUser(int id) {
		return userDao.deleteUser(id);
	}
	
	public boolean addUser(User user) {
		return userDao.addUser(user);
	}
}

6.dao的设计:

package com.yawn.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.yawn.entity.User;

@Repository
public class UserDao {

	@Autowired
	private SessionFactory sessionFactory;

	public UserDao() {
	}

	@SuppressWarnings("unchecked")
	public List<User> getAll() {

		Session session = getSession();

		String hql = "from User";

		Query query = session.createQuery(hql);

		return query.list();
	}

	public boolean updateUser(User user) {
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.update(user);
		tx.commit();
		session.close();
		return true;
	}

	public User getUserById(int id) {
		return (User) getSession().get(User.class, id);
	}

	public boolean deleteUser(int id) {

		User user = new User();
		user.setId(id);

		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.delete(user);
		tx.commit();
		session.close();
		return true;
	}

	public boolean addUser(User user) {

		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.save(user);
		tx.commit();
		session.close();
		return true;
	}

	private Session getSession() {
		return sessionFactory.openSession();
	}
}

7.entity的设计:

package com.yawn.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;

import org.hibernate.validator.constraints.Length;

@Entity
@Table(name="user")
public class User {
	
	/*
	 * @Id 定义数据表的主键
	 * @GeneratedValue 定义主键(列)的生成策略
	 */
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	@Column(length=24, unique=true, nullable=false)
//	@Length(max=24, min=3, message="name的长度在3~24之间")
	private String name;
	@Column(length=24, nullable=false)
	private String password;
	@Column
//	@Max(value=88, message="age不能大于88")
	private int age;
	
	public User() {
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password
				+ ", age=" + age + "]";
	}

}

8.页面设计:

-----------------addUser.jsp---------------------
<form action="/user2/addUser.do" method="post">
	name:<input name="name"><br>
	password:<input name="password"><br>
	age:<input name="age"><br>
	<input type="submit" value="添加">
</form>

-----------------getAll.jsp----------------------
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:forEach var="u" items="${userList }">
	<h3>${u.id } | ${u.name } | ${u.password } | ${u.age } |
		<a href="deleteUser/${u.id }.do">删除</a>
		<a href="updateUser/${u.id }.do">修改</a>
	</h3>
</c:forEach>

---------------updateUser.jsp--------------------
<form action="/user2/updateUser.do" method="post">
	<input name="id" type="hidden" value="${user.id }">
	name:<input name="name" value="${user.name }"><br>
	password:<input name="password" value="${user.password }"><br>
	age:<input name="age" value="${user.age }"><br>
	<input type="submit" value="确定修改">
</form>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档