springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能

转自:https://blog.csdn.net/thinkingcao/article/details/52472252

Cspringmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能

所用到的jar包

springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能

 

springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能

 

数据库

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

springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能

1.web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://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>

2.spring-comon.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.2.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!--扫描映射 -->
<context:component-scan base-package="com.ssh"></context:component-scan> <!-- 引入property配置文件 -->
<context:property-placeholder location="classpath:prop/jdbc.properties"></context:property-placeholder>
<!-- 配置数据源 -->
<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>
<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="com.ssh.entity"></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>
</beans>

3.spring-mvc.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 注解扫描包 -->
<context:component-scan base-package="com.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>

4. jdbc.properties

 # JDBC
# \u8BBE\u7F6E\u8FDE\u63A5\u6C60\u8FDE\u63A5\u65F6\u7684\u6570\u91CF
jdbc.initialSize=1
jdbc.filters=stat
# \u8FDE\u63A5\u6C60\u4E2D\u5B58\u5728\u7684\u6700\u5C0F\u8FDE\u63A5\u6570\u76EE\u3002\u8FDE\u63A5\u6C60\u4E2D\u8FDE\u63A5\u6570\u76EE\u53EF\u4EE5\u53D8\u5F88\u5C11\uFF0C\u5982\u679C\u4F7F\u7528\u4E86maxAge\u5C5E\u6027\uFF0C\u6709\u4E9B\u7A7A\u95F2\u7684\u8FDE\u63A5\u4F1A\u88AB\u5173\u95ED\u56E0\u4E3A\u79BB\u5B83\u6700\u8FD1\u4E00\u6B21\u8FDE\u63A5\u7684\u65F6\u95F4\u8FC7\u53BB\u592A\u4E45\u4E86\u3002\u4F46\u662F\uFF0C\u6211\u4EEC\u770B\u5230\u7684\u6253\u5F00\u7684\u8FDE\u63A5\u4E0D\u4F1A\u5C11\u4E8EminIdle\u3002
jdbc.minIdle=1
# \u8FDE\u63A5\u6570\u636E\u5E93\u7684\u6700\u5927\u8FDE\u63A5\u6570\u3002\u8FD9\u4E2A\u5C5E\u6027\u7528\u6765\u9650\u5236\u8FDE\u63A5\u6C60\u4E2D\u80FD\u591F\u6253\u5F00\u8FDE\u63A5\u7684\u6570\u91CF\uFF0C\u53EF\u4EE5\u65B9\u4FBF\u6570\u636E\u5E93\u505A\u8FDE\u63A5\u5BB9\u91CF\u89C4\u5212\u3002
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 \u6570\u636E\u5E93\u8FDE\u63A5\u65B9\u5F0F
#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 \u6570\u636E\u5E93\u8FDE\u63A5\u65B9\u5F0F
jdbc.mysql.driverClassName=com.mysql.jdbc.Driver
jdbc.mysql.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
jdbc.mysql.username=root
jdbc.mysql.password=123456
jdbc.mysql.dialect=org.hibernate.dialect.MySQL5InnoDBDialect #HIBERNATE
jdbc.show_sql=false
jdbc.format_sql=false

5.

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

6.

 package com.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 + "]";
} }

7.

 package com.ssh.dao;

 import java.util.List;

 import com.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;
}

8.

 package com.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 com.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 (User) 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();
}
}

9.

 package com.ssh.service;

 import java.util.List;

 import com.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;
}

10.

 package com.ssh.service;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.ssh.dao.UserDao;
import com.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);
}
}

11.

 package com.ssh.controller;

 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 com.ssh.entity.User;
import com.ssh.path.Path;
import com.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"; }
}

12.

 package com.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 com.ssh.dao.UserDao;
import com.ssh.entity.User;
import com.ssh.service.UserService; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/spring-common.xml")
@Transactional
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.err.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);
}
}

13.

 package com.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";
}

14.

 package com.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 com.ssh.dao.UserDao;
import com.ssh.entity.User;
import com.ssh.service.UserService; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/spring-common.xml")
@Transactional
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.err.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);
}
}

springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能

上一篇:COJ 0501 取数游戏(TPM)


下一篇:sql server无log ldf日志文件附件mdf数据库重新生成ldf日志文件