频道栏目
首页 > 程序开发 > 软件开发 > Java > 正文
springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能
2016-05-12 09:07:50         来源:低调如我的博客  
收藏   我要投稿

项目开发环境

1.Eclipse    2.tomcat7.0    3.MySQL

项目的整体架构

\

所用到的jar包

\

\

数据库

数据库表就不用教大家了,一张表,很简单的,下面是我建好的表

\

 

下面是web.xml的详情信息

<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app id="WebApp_ID" version="2.5" xmlns="https://java.sun.com/xml/ns/javaee" xmlns:web="https://java.sun.com/xml/ns/javaee" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>json_test</display-name>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/spring-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</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:spring/spring-mvc.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>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>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <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></pre>
<p style="text-align: left;">&nbsp;</p>
<p style="text-align: left;">&nbsp;</p>
<h3 style="text-align: left;">下面是spring-common.xml的详情信息</h3>
<p style="text-align: left;">&nbsp;</p>
<pre class="brush:java;" style="text-align: left;">
<!--?xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="https://www.springframework.org/schema/beans" xmlns:aop="https://www.springframework.org/schema/aop" xmlns:cache="https://www.springframework.org/schema/cache" xmlns:context="https://www.springframework.org/schema/context" xmlns:jdbc="https://www.springframework.org/schema/jdbc" xmlns:jee="https://www.springframework.org/schema/jee" xmlns:jms="https://www.springframework.org/schema/jms" xmlns:lang="https://www.springframework.org/schema/lang" xmlns:mvc="https://www.springframework.org/schema/mvc" xmlns:oxm="https://www.springframework.org/schema/oxm" xmlns:task="https://www.springframework.org/schema/task" xmlns:tx="https://www.springframework.org/schema/tx" xmlns:util="https://www.springframework.org/schema/util" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
    https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-4.0.xsd
    https://www.springframework.org/schema/cache https://www.springframework.org/schema/cache/spring-cache-4.0.xsd
    https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-4.0.xsd
    https://www.springframework.org/schema/jdbc https://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
    https://www.springframework.org/schema/jee https://www.springframework.org/schema/jee/spring-jee-4.0.xsd
    https://www.springframework.org/schema/jms https://www.springframework.org/schema/jms/spring-jms-4.0.xsd
    https://www.springframework.org/schema/lang https://www.springframework.org/schema/lang/spring-lang-4.0.xsd
    https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    https://www.springframework.org/schema/oxm https://www.springframework.org/schema/oxm/spring-oxm-4.0.xsd
    https://www.springframework.org/schema/task https://www.springframework.org/schema/task/spring-task-4.0.xsd
    https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    https://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
	<!--扫描映射  -->
	<context:component-scan base-package="ssh">
	
	<!-- 引入property配置文件 -->
	<context:property-placeholder location="classpath:prop/jdbc.properties">
		
	<!-- 配置数据源 -->
	<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
		<property name="driverClassName" value="${jdbc.mysql.driverClassName}"></property>
		<property name="url" value="${jdbc.mysql.url}"></property>
		<property name="username" value="${jdbc.mysql.username}"></property>
		<property name="password" value="${jdbc.mysql.password}"></property>
		<!-- 初始化连接大小
		<property name="initialSize" value="${jdbc.initialSize}"></property> -->
		<!-- 连接池最大数量 
		<property name="maxActive" value="${jdbc.maxActive}"></property>-->
		<!-- 连接池最大空闲 -->
		<!-- <property name="maxIdle" value="${maxIdle}"></property> -->
		<!-- 连接池最小空闲 
		<property name="minIdle" value="${jdbc.minIdle}"></property>-->
		<!-- 获取连接最大等待时间 
		<property name="maxWait" value="${jdbc.maxWait}"></property>-->
	</bean>
	
	<!-- 配置SessionFactory -->
	<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
		<property name="dataSource" ref="dataSource">
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${jdbc.mysql.dialect}</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<!--是否显示sql语句 我在这里是显示的  -->
				<prop key="hibernate.show_sql">true</prop>
				<!--格式化显示sql语句  -->
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
		<!-- 自动扫描制定位置下的实体进行映射  --> 
    	<property name="packagesToScan" value="ssh.entity">
	</property></property></bean>
	
	<!-- 配置一个事务管理器 -->
	<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="transactionManager">
		<property name="sessionFactory" ref="sessionFactory">
	</property></bean>
	
	<!-- 应该是开启事物 -->
	<tx:annotation-driven transaction-manager="transactionManager">
	
</tx:annotation-driven></context:property-placeholder></context:component-scan></beans></pre>
<p style="text-align: left;">&nbsp;</p>
<p style="text-align: left;">&nbsp;</p>
<h3 style="text-align: left;">下面是spring-mvc.xml的详情信息</h3>
<p style="text-align: left;">&nbsp;</p>
<pre class="brush:java;" style="text-align: left;">
<!--?xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="https://www.springframework.org/schema/beans" xmlns:context="https://www.springframework.org/schema/context" xmlns:mvc="https://www.springframework.org/schema/mvc" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="https://www.springframework.org/schema/beans 
	https://www.springframework.org/schema/beans/spring-beans.xsd
	https://www.springframework.org/schema/context
	https://www.springframework.org/schema/context/spring-context-3.2.xsd
	https://www.springframework.org/schema/mvc
	https://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
	
	<!-- 注解扫描包 -->
	<context:component-scan base-package="ssh">

	<!-- 开启注解 -->
	<mvc:annotation-driven>		

	<!-- 定义视图解析器 -->	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</mvc:annotation-driven></context:component-scan></beans>

Hibernate用于连接数据库的小配置文件jdbc.properties的详情信息

 

# JDBC
# 设置连接池连接时的数量
jdbc.initialSize=1
jdbc.filters=stat
# 连接池中存在的最小连接数目。连接池中连接数目可以变很少,如果使用了maxAge属性,有些空闲的连接会被关闭因为离它最近一次连接的时间过去太久了。但是,我们看到的打开的连接不会少于minIdle。
jdbc.minIdle=1
# 连接数据库的最大连接数。这个属性用来限制连接池中能够打开连接的数量,可以方便数据库做连接容量规划。
jdbc.maxActive=99
jdbc.maxWait=1000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.poolPreparedStatements=true
jdbc.maxPoolPreparedStatementPerConnectionSize=50
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.validationQuery=select 1 from dual

jdbc.removeAbandonedTimeout=150  
jdbc.logAbandoned=true
jdbc.removeAbandoned=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false


#ORACLE 数据库连接方式
#jdbc.oracle.driverClassName=oracle.jdbc.driver.OracleDriver
#jdbc.oracle.url=jdbc\:oracle\:thin\:@localhost\:1521\:orcl
#jdbc.oracle.username=wrg
#jdbc.oracle.password=wrg
#jdbc.oracle.dialect=org.hibernate.dialect.Oracle10gDialect



# MYSQL 数据库连接方式
jdbc.mysql.driverClassName=com.mysql.jdbc.Driver
jdbc.mysql.url=jdbc:mysql://localhost:3806/springmvc?characterEncoding=UTF-8
jdbc.mysql.username=root
jdbc.mysql.password=HZIMS_GP
jdbc.mysql.dialect=org.hibernate.dialect.MySQL5InnoDBDialect


#HIBERNATE
jdbc.show_sql=false
jdbc.format_sql=false


 

下面是log4j.properties日志文件的详情信息

 

#console log
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c - %m%n


#logger
log4j.logger.org.springframework=DEBUG,CONSOLE
log4j.logger.org.hibernate=INFO,CONSOLE
log4j.logger.org.apache=INFO,CONSOLE



log4j.rootLogger=DEBUG,CONSOLE

 

 

创建Entity类User实体

 

package ssh.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="TUSER")
public class User{	
	@Id
	@GeneratedValue(generator="id")
	@GenericGenerator(name = "id",strategy="identity")
	private Integer id;
	private String name;
	private String password;	
	@Column(name="LOGIN_DATE")
	private String loginDate;
	public Integer getId() {
		return id;
	}
	public void setId(Integer 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 String getLoginDate() {
		return loginDate;
	}
	public void setLoginDate(String loginDate) {
		this.loginDate = loginDate;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password
				+ ", loginDate=" + loginDate + "]";
	}
	
}

 

 

创建Dao层接口

 

package ssh.dao;
import java.util.List;
import ssh.entity.User;
public interface UserDao {
	//登录
	User selectUser(User user) throws Exception;
	//查询所有
	List getAllUsers() throws Exception;
	//添加用户
	void addUser(User user) throws Exception;
	//删除用户
	void delUser(Integer id) throws Exception;
	//修改用户
	void updateUser(User user) throws Exception;
	//单个查询
	User getUser(Integer id) throws Exception ;
}

 

 

Dao层接口的实现

 

package ssh.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import ssh.entity.User;
@Repository
@SuppressWarnings("unchecked")
public class UserDaoImpl implements UserDao {
	@Autowired
	private SessionFactory sessionFactory;
	//登录
	public User selectUser(User user) throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.name=? and u.password=?");
		query.setString(0, user.getName());
		query.setString(1, user.getPassword());
		List list = query.list();
		if(list==null||list.size()==0){
			throw new RuntimeException("查询失败");
		}
		return list.get(0);
	}
	
	//查询所有
	public List getAllUsers() throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery("from User");
		List list = query.list();
		return list;
	}
	
	//单个查询
	public User getUser(Integer id) throws Exception {
		return (User) sessionFactory.getCurrentSession().createQuery("from User u where u.id ="+id).uniqueResult();
	}

	//添加用户
	public void addUser(User user) throws Exception {
		System.out.println("11111111111111111"+user.getName());
		sessionFactory.getCurrentSession().save(user);
	}
	
	//删除用户
	public void delUser(Integer id) throws Exception {
		sessionFactory.getCurrentSession().createQuery("delete User u where u.id="+id).executeUpdate();	   	
		
	}
	
	//修改用户
	public void updateUser(User user) throws Exception {
		 Session session = sessionFactory.getCurrentSession();
		 session.beginTransaction();
		 String hql = ("update User u set u.name = ?,u.password = ?,u.loginDate = ? where u.id = ?");  
		 Query query = session.createQuery(hql);
		 query.setParameter(0, user.getName());
		 query.setParameter(1, user.getPassword());
		 query.setParameter(2, user.getLoginDate());
		 query.setParameter(3, user.getId());
		 query.executeUpdate();
		 session.getTransaction().commit(); 			
	}
}

 

创建Service层的接口

package ssh.service;
import java.util.List;
import ssh.entity.User;
public interface UserService {
	//登录
	User selectUser(User user ) throws Exception;
	//查询所有
	List getAllUsers() throws Exception;
	//添加用户
	void addUser(User user) throws Exception;
	//删除用户
	void delUser(Integer id) throws Exception;	
	//修改用户
	void updateUser(User user) throws Exception;	
	//单个查询
	User getUser(Integer id) throws Exception;
}

 

Service层的接口的实现

 

package ssh.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ssh.dao.UserDao;
import ssh.entity.User;
@Service("userService")
public class UserServiceImpl implements UserService{
	@Autowired
	private UserDao userDao;
	//登录
	public User selectUser(User user) throws Exception {
		return userDao.selectUser(user);
	}
	
	//单个查询
	public User getUser(Integer id) throws Exception {
		return userDao.getUser(id);			
	}  
	//查询所有
	public List getAllUsers() throws Exception {
		List users = userDao.getAllUsers();		
		return users;
	}
	
	//添加用户
	public void addUser(User user) throws Exception {
		userDao.addUser(user);	
	}
	//删除用户
	
	public void delUser(Integer id) throws Exception {		 
		userDao.delUser(id);
	}
	//修改用户
	public void updateUser(User user) throws Exception {
		userDao.updateUser(user);		
	}  	
}

 

 

控制层Action层的代码如下

 

package ssh.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ssh.entity.User;
import ssh.path.Path;
import ssh.service.UserService;
@Controller
@RequestMapping(value=Path.USER)
public class UserAction {	
	@Autowired
	private UserService userService;
	@RequestMapping(value=Path.LOGIN_INDEX)
	public String login(HttpServletRequest request, HttpServletResponse response) throws Exception{
		return Path.LOGIN_INDEX;
	}
		
	@RequestMapping(value=Path.LOGIN_OK,method=RequestMethod.POST)
	public String loginCheck(User user,HttpServletRequest request, HttpServletResponse response) throws Exception{
		response.setContentType("text/html;charset=utf-8");
		User u = userService.selectUser(user);
		System.out.println("user is ------------------------ "+u);
		request.setAttribute("user", u);
		return "redirect:/user/index.do";
		}
	
	//单个查询
	@RequestMapping(value=Path.GET_USER)  
	public String getUser(Integer id,HttpServletRequest request) throws Exception{  
	    request.setAttribute("user", userService.getUser(id));  
	    return Path.UPDATE_USER;  
	} 
	
	//查询所有
	@RequestMapping(value=Path.INDEX)
	public String getAllUsers(HttpServletRequest request) throws Exception{
		request.setAttribute("userList", userService.getAllUsers());
		return Path.INDEX;
	}
	//添加跳转方法
	@RequestMapping(value=Path.TO_ADDUSER)  
	public String toAddUser(){  
	    return Path.ADD_USER;  
	}		
	//添加用户
	@RequestMapping(value=Path.ADD_USER)
	public String addUser(User user,HttpServletRequest request) throws Exception{
		System.out.println("用户名:======"+user.getName());
		userService.addUser(user);
		return "redirect:/user/index.do";
	}
	
	//删除用户
	@RequestMapping(value=Path.DEL_USER)
	public String delUser(Integer id,HttpServletResponse response) throws Exception{  
	    userService.delUser(id);
	    return "redirect:/user/index.do";
	}  
	
	//更新用户
	@RequestMapping(value=Path.UPDATE_USER)
	public String  updateUser(User user,HttpServletRequest request) throws Exception{
		
		userService.updateUser(user);
		user = userService .getUser(user.getId());
		request.setAttribute("user", user);		
		return "redirect:/user/index.do";
		
	}					
}

 

 

全局路径Path的代码

 

package ssh.path;
public class Path {
	public static final String USER = "/user";
	/**
	 * 登陆
	 */
	public static final String LOGIN_INDEX = "/login";
	/**
	 * 登陆成功
	 */
	public static final String LOGIN_OK = "/loginok";
	
	/**
	 * 查询所有
	 */
	public static final String INDEX = "/index";
	/**
	 * 添加用户
	 */
	public static final String ADD_USER = "/addUser";
	
	/**
	 * 跳转添加用户
	 */
	public static final String TO_ADDUSER = "/toaddUser";
	
	/**
	 * 删除用户
	 */
	public static final String DEL_USER = "/delUser";
	
	/**
	 * 更新用户
	 */
	public static final String UPDATE_USER = "/updateUser";
	
	/**
	 * 跳转更新用户
	 */
	public static final String GET_USER = "/getUser";		
}

 

 

测试类Test的代码

 

package ssh.test;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import ssh.dao.UserDao;
import ssh.entity.User;
import ssh.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/spring-common.xml")
@Transactional
/**
 * 
 * @author hello
 *	说明:在这里 所有实例化的注解我都使用 @Autowrited (spring通用的)
 *						      也可以使用 @Resource   (J2EE通用的)
 *						      两者区别百度
 */
public class TestAll {
	@Autowired
	private SessionFactory sessionFactory;
	/**
	 * 测试sessionfactory
	 * 测试时 spring-common 不能存在 事物bean
	 * 					      不能存在 事物管理器 bean
	 * 					      不能存在dao
	 * 					      不能存在service
	 * 					      不能存在action
	 * 只是为了防止当其他内容写错时 sessionfactory也开启不了 除非是其他的bean没有错
	 */
	@Test
	public void testSf(){
		System.out.println("测试开启");
		System.out.println("   sessionfactory = "+sessionFactory);
		System.out.println("测试完成");
	}
	/**
	 * 测试UserDao
	 */
	@Autowired
	private UserDao userDao;
	@Test
	public void testUserDao() throws Exception{
		User u = new User();
		u.setName("admin");
		u.setPassword("12345678");
		User user  = userDao.selectUser(u);
		System.out.println("user is "+user);
		userDao.addUser(u);
	}					
	/**
	 * 测试UserService
	 */
	@Autowired
	private UserService userService;
	@Test
	public void testUserService() throws Exception{
		User u = new User();
		u.setName("admin");
		u.setPassword("12345678");
		User user = userService.selectUser(u);
		System.out.println("user is "+user);
	}
}

 

登录界面login.jsp的代码

 

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<script type="text/javascript" src="../js/jquery-1.8.3.js"></script>

用户登录

用户名: 密码:

 

 

查询所有index.jsp页面的代码

 

<%@ page="" language="java" contenttype="text/html; charset=UTF-8" pageencoding="UTF-8">  
<%@taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core">

<% string="" path="request.getContextPath();">
<!--{cke_protected}%3Cscript%20type%3D%22text%2Fjavascript%22%20src%3D%22%3C%25%3Dpath%25%3E%2Fjs%2Fjquery-1.9.1.min.js%22%3E%3C%2Fscript%3E-->
<h1 style="text-align: left;"><a href="https://blog.csdn.net/spring_springmvc_hibernate/user/toaddUser.do">添加用户</a></h1>
<table border="1" class="t">
<tbody style="text-align: left;">
</tbody>
<tbody>
	<tr>
	<td style="text-align: left;">&nbsp;</td>
	<td style="text-align: left;">&nbsp;</td>
	</tr>
</tbody>
</table>
<p style="text-align: left;"><br />
&lt;%@ page=&quot;&quot; language=&quot;java&quot; contenttype=&quot;text/html; charset=UTF-8&quot; pageencoding=&quot;UTF-8&quot;&gt;&lt;%@taglib prefix=&quot;c&quot; uri=&quot;https://java.sun.com/jsp/jstl/core&quot;&gt;<!--!doctype--><!--%@taglib--><!--%@--></p>

 


						
点击复制链接 与好友分享!回本站首页
相关TAG标签 框架 功能
上一篇:Spring对ORM的支持之集成Hibernate3
下一篇:Spring注入:配置与注解
相关文章
图文推荐
文章
推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站