springmvc4+hibernate4整合框架的搭建,超详细哦

                       

放假了!周六日休息!来北京真的不容易呀!和他们一起租房虽然便宜吧!但是周六都在打游戏!无赖,只能来公司了,前几天一直纠结于怎么搭建springmvc+hibernate整合框架,百度了一番,各种报错的情况,最终算是搭建好了吧!其实对于我个人来说,以前做Android开发和 Struts+spring+hibernate的网站开发来说,springmvc+hibernate应该是没有什么问题的,凡事都得动手,没有看出来的技术,只有实践的真理!下面我们来看看搭建过程吧
项目源码https://github.com/twjitm/sj 这是我的GitHub,欢迎star。
NO.1
创建一个web项目
这里写图片描述
在WEB-INF下面创建lib文件夹,用于管理各种jar包
No.2
准备各种必备的jar包,如下图所示
这里写图片描述

No.3
配置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">  <display-name>test_ssh</display-name>  <welcome-file-list>    <welcome-file>login.jsp</welcome-file>  </welcome-file-list>  <!-- 加载所有的配置文件 -->  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath*:config/spring/applicationContext.xml</param-value>  </context-param>  <!-- 配置Spring监听 -->  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <!-- 配置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*:config/spring/spring-servlet.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>springMVC</servlet-name>    <url-pattern>/</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>  <!-- 配置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>
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

No.4
配置applicationContext.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:p="http://www.springframework.org/schema/p"    xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:jaxws="http://cxf.apache.org/jaxws"    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">    <!--需要引入的配置文件            <import resource="classpath:META-INF/cxf/cxf.xml"/>            <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>            <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>-->         <context:component-scan base-package="com.tgb.*" />        <!-- 开启注释处理器 -->        <context:annotation-config/>        <!-- 配置数据源 -->        <context:property-placeholder location="classpath*:config/spring/jdbc.properties" />    <!-- 配置数据源 -->    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>        <property name="url" value="jdbc:mysql://127.0.0.1:3306/lrdb"></property>        <property name="username" value="root"></property><!--        <property name="password" value="1"></property> -->    </bean>    <bean id="sessionFactory"        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">        <property name="dataSource"><ref bean="dataSource" /></property>        <!-- 扫描实体(pojo) -->        <property name="namingStrategy">        <bean class="org.hibernate.cfg.ImprovedNamingStrategy"></bean>        </property>        <property name="hibernateProperties">            <!-- 这个是以前的配置方法<props>                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>                <prop key="hibernate.dialect">${hibernate.dialect}</prop>                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>            </props> -->            <props>            <prop key="hibernate.show_sql">org.hibernate.dialect.MySQLInnoDBDialect</prop>            <prop key="hibernate.show_sql">true</prop>            <prop key="hibernate.format_sql">true</prop>            <prop key="hibernate.hbm2ddl.auto">update</prop>            </props>        </property>        <!-- 自动扫描实体包 -->        <property name="packagesToScan">            <list>                <value>com.tgb.entity</value>                <value>com.tgb.entity.view</value>            </list>        </property>    </bean>    <!-- 实物管理器 -->    <bean id="transactionManager"        class="org.springframework.orm.hibernate4.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory" />    </bean>    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="add*" />            <tx:method name="save*" />            <tx:method name="update*" />            <tx:method name="modify*" />            <tx:method name="edit*" />            <tx:method name="delete*" />            <tx:method name="remove*" />            <tx:method name="change*" />            <tx:method name="repair" />            <tx:method name="deleteAndRepair" />            <tx:method name="get*" propagation="SUPPORTS" />            <tx:method name="find*" propagation="SUPPORTS" />            <tx:method name="load*" propagation="SUPPORTS" />            <tx:method name="search*" propagation="SUPPORTS" />            <tx:method name="datagrid*" propagation="SUPPORTS" />            <tx:method name="*" propagation="SUPPORTS" />        </tx:attributes>    </tx:advice>    <aop:config proxy-target-class="true">        <aop:pointcut id="transactionPointcut" expression="execution(* com.tgb.service.*.*(..))" />        <aop:advisor pointcut-ref="transactionPointcut"            advice-ref="transactionAdvice" />    </aop:config>    <!-- 注解方式配置事物 -->    <tx:annotation-driven transaction-manager="transactionManager"/>    </beans>
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96

No.5配置spring-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"    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.tgb" />    <!-- 开启注解 -->    <mvc:annotation-driven />    <!-- 静态资源(js/image)的访问 -->    <mvc:resources location="/js/" mapping="/js/**"/>    <!-- 定义视图解析器 -->        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/"></property>        <property name="suffix" value=".jsp"></property>    </bean></beans>
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

No.6配置jdbc.properties文件

proxool.alias=lrdbproxool.file=proxool.xmlproxool.providerClass=org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider proxool.maxConnCount=100proxool.minConnCount=10proxool.statistics=1m,15m,1h,1dproxool.simultaneousBuildThrottle=5proxool.trace=falseproxool.verbose=falsejdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://127.0.0.1:3306/dbnamejdbc.username=rootjdbc.password=hibernate.hbm2ddl.auto=nonehibernate.show_sql=truehibernate.format_sql=truehibernate.dialect=org.hibernate.dialect.MySQLDialecthibernate.temp.use_jdbc_metadata_defaults=false
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

测试:
到这里,环境基本搭建完成了,写代码测试一下
首先看看代码的结构图
这里写图片描述
数据库表设计
这里写图片描述
为了方便测试环境框架就建立了一个简简单单的实体类
dao层代码

package com.tgb.dao;import java.util.List;import com.tgb.entity.User;public interface IUserDao {    public User getUser(String id);    public List<User> getAllUser();    public void addUser(User user);    public boolean delUser(String id);    public boolean updateUser(User user);}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

dao实现类

package com.tgb.dao;import java.util.List;import javax.annotation.Resource;import org.hibernate.Query;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import com.tgb.base.BaseDao;import com.tgb.entity.User;@Repositorypublic class UserDao implements IUserDao {     @Autowired    private SessionFactory sessionFactory;     @Resource     private BaseDao<User> baseDao;    public void setSessionFactory(SessionFactory sessionFactory) {        this.sessionFactory = sessionFactory;    }    @Override    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();    }    @Override    public List<User> getAllUser() {        String hql = "from User";        //baseDao.find(hql);        //Query query = sessionFactory.getCurrentSession().createQuery(hql);        return baseDao.find(hql);    }    @Override    public void addUser(User user) {        sessionFactory.getCurrentSession().save(user);    }    @Override    public boolean delUser(String id) {        String hql = "delete User u where u.id = ?";        Query query = sessionFactory.getCurrentSession().createQuery(hql);        query.setString(0, id);        return (query.executeUpdate() > 0);    }    @Override    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.setString(1, user.getAge());        query.setString(2, user.getId());        return (query.executeUpdate() > 0);    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

service层方法

package com.tgb.service;import java.util.List;import com.tgb.entity.User;public interface IUserService {    public User getUser(String id);    public List<User> getAllUser();    public void addUser(User user);    public boolean delUser(String id);    public boolean updateUser(User user);}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

service实现类

package com.tgb.service;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.tgb.dao.IUserDao;import com.tgb.entity.User;@Servicepublic class UserService implements IUserService {    @Resource    private IUserDao userDao;    public void setUserDao(IUserDao userDao) {        this.userDao = userDao;    }    @Override    public User getUser(String id) {        return userDao.getUser(id);    }    @Override    public List<User> getAllUser() {        return userDao.getAllUser();    }    @Override    public void addUser(User user) {        userDao.addUser(user);    }    @Override    public boolean delUser(String id) {        return userDao.delUser(id);    }    @Override    public boolean updateUser(User user) {        return userDao.updateUser(user);    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

controller层

package com.tgb.controller;import java.io.IOException;import java.io.PrintWriter;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.RequestMapping;import com.tgb.entity.User;import com.tgb.service.IUserService;@Controller@RequestMapping("/user")public class UserController {    @Resource    private IUserService userService;    @RequestMapping("/getAllUser")    public String getAllUser(HttpServletRequest request){        request.setAttribute("userList", userService.getAllUser());        return "/index";    }    @RequestMapping("/getUser")    public String getUser(String id,HttpServletRequest request){        request.setAttribute("user", userService.getUser(id));        return "/editUser";    }    @RequestMapping("/toAddUser")    public String toAddUser(){        return "/addUser";    }    @RequestMapping("/addUser")    public String addUser(User user,HttpServletRequest request){        userService.addUser(user);        return "redirect:/user/getAllUser";    }    @RequestMapping("/delUser")    public void delUser(String id,HttpServletResponse response){        String result = "{\"result\":\"error\"}";        if(userService.delUser(id)){            result = "{\"result\":\"success\"}";        }        response.setContentType("application/json");        try {            PrintWriter out = response.getWriter();            out.write(result);        } catch (IOException e) {            e.printStackTrace();        }    }    @RequestMapping("/updateUser")    public String updateUser(User user,HttpServletRequest request){        if(userService.updateUser(user)){            user = userService.getUser(user.getId());            request.setAttribute("user", user);            return "redirect:/user/getAllUser";        }else{            return "/error";        }    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77

看看效果,虽然简单,足以说明问题
这里写图片描述
这里写图片描述
到此,springmvc+spring+hibernate框架搭建完成,其实我是想在家的时候无聊写写js才弄这个框架的,哎,我们公司要求我们必须啥都会,我一个后台程序员,不说了,调css去了,要源码的小伙伴留下邮箱!当晚必发!!!!!!!!

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值