博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springmvc、spring、hibernate整合示例
阅读量:6081 次
发布时间:2019-06-20

本文共 7396 字,大约阅读时间需要 24 分钟。

hot3.png

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

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

org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:beans.xml
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:user-servlet.xml
1
springmvc
*.do
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
characterEncodingFilter
/*

2.spring mvc配置文件 user-servlet.xml:

3.spring的配置文件beans.xml:

org.hibernate.dialect.MySQLDialect
update
true
true
com.yawn.entity.User

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

########################################	configuration of database		########################################jdbc.jdbcUrl=jdbc\:mysql\://localhost\:3306/volunteer?useUnicode\=true&characterEncoding\=utf8jdbc.driverClass=com.mysql.jdbc.Driverjdbc.user=rootjdbc.password=rootjdbc.initialPoolSize=20jdbc.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;@Controllerpublic class UserController {		@Autowired	private UserService userService;	public UserController() {	}		@RequestMapping("getAll")	private List
getAll() { return userService.getAll(); } @RequestMapping(value="updateUser/{id}", method={RequestMethod.GET}) private String updateUser(@PathVariable int id, Map
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;@Servicepublic class UserService {		@Autowired	private UserDao userDao;	public UserService() {	}		public List
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;@Repositorypublic class UserDao {	@Autowired	private SessionFactory sessionFactory;	public UserDao() {	}	@SuppressWarnings("unchecked")	public List
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---------------------
name:
password:
age:
-----------------getAll.jsp----------------------<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

${u.id } | ${u.name } | ${u.password } | ${u.age } | 删除 修改

---------------updateUser.jsp--------------------
name:
password:
age:

 

转载于:https://my.oschina.net/silenceyawen/blog/673350

你可能感兴趣的文章
Javascript中闭包(Closure)的探索(一)-基本概念
查看>>
spark高级排序彻底解秘
查看>>
ylbtech-LanguageSamples-PartialTypes(部分类型)
查看>>
福建省促进大数据发展:变分散式管理为统筹集中式管理
查看>>
开发环境、生产环境、测试环境的基本理解和区别
查看>>
tomcat多应用之间如何共享jar
查看>>
Flex前后台交互,service层调用后台服务的简单封装
查看>>
MySQL入门12-数据类型
查看>>
Windows Azure 保留已存在的虚拟网络外网IP(云服务)
查看>>
修改字符集
查看>>
HackTheGame 攻略 - 第四关
查看>>
js删除数组元素
查看>>
带空格文件名的处理(find xargs grep ..etc)
查看>>
华为Access、Hybrid和Trunk的区别和设置
查看>>
centos使用docker下安装mysql并配置、nginx
查看>>
关于HTML5的理解
查看>>
需要学的东西
查看>>
Internet Message Access Protocol --- IMAP协议
查看>>
Linux 获取文件夹下的所有文件
查看>>
对 Sea.js 进行配置(一) seajs.config
查看>>