spring,springMvc和hibernate整合

一:配置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"
    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>hibernate-Spring</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
        /WEB-INF/classes/applicationContext.xml
        </param-value>
    </context-param>
    <servlet>
        <servlet-name>mySpring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
              /WEB-INF/classes/mySpring-servlet.xml
          </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mySpring</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!-- hibernate4.0必须 -->
    <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>sessionFactoryBeanName</param-name>
            <param-value>sessionFactory</param-value>
        </init-param>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>flushMode</param-name>
            <param-value>AUTO</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>hibernateFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-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>
</web-app>

二:在WEB-INF下创建classes文件,里面放置配置文件,包括:

2.1: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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    <!--启用自动扫描 -->
    <context:component-scan base-package="com.wode">
         <context:exclude-filter type="regex" expression=".(dao|service.impl)"
            />
    </context:component-scan>
    <aop:aspectj-autoproxy />
    <!-- 配置C3P0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl"
            value="jdbc:mysql://localhost:3306/j116?characterEncoding=utf-8" />
        <property name="user" value="root" />
        <property name="password" value="admin" />
        <property name="minPoolSize" value="1" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="60" />
        <property name="initialPoolSize" value="1" />
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
        <property name="acquireIncrement" value="5" />
        <property name="automaticTestTable" value="c3p0TestTable" />
        <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
        <property name="idleConnectionTestPeriod" value="60" />
        <property name="checkoutTimeout" value="3000" />
    </bean>

    <!-- 配置SessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 向SessionFactory中注入数据源 -->
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <!-- 定义Hibernate的方言 -->
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <!-- 是否根据需要每次自动更新数据库 <prop key="hibernate.hbm2ddl.auto">update</prop> -->
                <!-- 控制台显示SQL -->
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <!-- 使用SQL注释 -->
                <prop key="hibernate.use_sql_comments">true</prop>
            </props>
        </property>

        <!-- 浏览entitys包下的所有使用Hibernate注解的JavaBean -->
        <property name="packagesToScan">
            <list>
                <value>com.wode.bean</value>
            </list>
        </property>

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

    <!-- 事物配置的模板-偷的 -->
    <!-- 定义个通知,指定事务管理器 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" read-only="false"
                rollback-for="java.lang.Exception" />
            <tx:method name="save*" propagation="REQUIRED" read-only="false"
                rollback-for="java.lang.Exception" />
            <tx:method name="update*" propagation="REQUIRED" read-only="false"
                rollback-for="java.lang.Exception" />
            <tx:method name="load*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="userPointCut" expression="execution(* com.wode.service.*.*(..))" />
        <aop:aspect id="logAspect" ref="userLogger">
            <aop:before method="testLogger" pointcut-ref="userPointCut"></aop:before>
        </aop:aspect>
    </aop:config>

</beans>

2.2:mySpring-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:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

    <mvc:annotation-driven />

    <context:component-scan base-package="com.wode.controller" />

    <!-- ViewResolver视图解析器 用于将返回的ModelAndView对象进行分离 -->
    <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

3:导入核心jar包,放入WEB-INF/lib里面:

4:在src中创建项目,项目结构如下:(根据自己情况命名,尽量按照三层架构的方式创建)

5:创建数据库(省略。。。注意数据库中变量的名字与bean中的Column对应)

6:创建UserBean:

package com.wode.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="users")
public class User implements Serializable{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="user_id")
    private int userId;
    @Column(name="user_name")
    private String userName;
    @Column(name="user_pwd")
    private String userPwd;
    @Column(name="user_type")
    private int userType;
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPwd() {
        return userPwd;
    }
    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }
    public int getUserType() {
        return userType;
    }
    public void setUserType(int userType) {
        this.userType = userType;
    }
}

7:创建dao层和service层的接口:

8:创建dao层的实现类:

package com.wode.dao.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.wode.bean.User;
import com.wode.dao.UserDao;

@Repository
public class UserDaoImpl implements UserDao{
    @Autowired
    @Qualifier("sessionFactory")
    //等价于@Resource
    private SessionFactory sessionFactory;
    public void addUser(User user){
        Session session=sessionFactory.getCurrentSession();
        session.save(user);
    }
}

9:创建service层的实现类:

package com.wode.service.impl;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.wode.bean.User;
import com.wode.dao.UserDao;
import com.wode.service.UserService;

@Service
public class UserServiceImpl implements UserService{
    @Resource(name="userDaoImpl")
    private UserDao userDao;
    //在接口定义常量
    public void login(String name,String pwd){
        System.out.println("数据库查询了"+name+" "+pwd);
    }
    public void addUser(User user){
        System.out.println(user.getUserName()+" "+user.getUserPwd());
        user.setUserType(1);
        userDao.addUser(user);
    }
}

10:创建Controller层对象

package com.wode.controller;

import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.wode.bean.User;
import com.wode.service.UserService;

@Controller
public class UserController {
    @Resource(name="userServiceImpl")
    private UserService service;
    @RequestMapping("regist.do")
    public String login(User user){
        service.addUser(user);
        return "success";
    }
}

11:创建Aop切面,记录日志:

package com.wode.log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component("userLogger")
public class UserLogger {
    public int testLogger(JoinPoint jpt) throws Throwable{
        System.out.println("前置记录日志");
        return 1;
    }
}

12:如果需要JUnit测试,则需要注意:

package com.wode.dao;
import static org.junit.Assert.*;

import javax.annotation.Resource;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import com.wode.bean.User;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="../../../applicationContext.xml")//这里路径和文件根据自己情况适当修改
@Transactional //这里是关键点
public class TestUserDao {
    @Resource(name="userDaoImpl")
    private UserDao userDao;
    @Test
    public void addUserTest() {
            User user=new User();
            user.setUserName("hehe");
            user.setUserPwd("admin");
            userDao.addUser(user);
    }

}
时间: 2024-09-29 10:24:06

spring,springMvc和hibernate整合的相关文章

Spring Security 4 Hibernate整合 注解和xml例子(带源码)

[相关已翻译的本系列其他文章,点击分类里面的spring security 4] [ 翻译by 明明如月 QQ 605283073] 上一篇文章:Spring Security 4 基于角色的登录例子(带源码) 下一篇文章:Spring Security 4 整合Hibernate Bcrypt密码加密(带源码) 原文地址:http://websystique.com/spring-security/spring-security-4-hibernate-annotation-example/

SSM Spring SpringMVC Mybatis框架整合Java配置完整版

以前用着SSH都是老师给配好的,自己直接改就可以.但是公司主流还是SSM,就自己研究了一下Java版本的配置.网上大多是基于xnl的配置,但是越往后越新的项目都开始基于JavaConfig配置了,这也是写此文章的原因.不论是eclipse还是myeclipse 都没有集成mybatis的相关组件,Spring也没有对其进行兼容,所以说我们会用到一些mybatis提供的核心jar包.下面先看一下我们的项目结构,我先自建了一个集成spring4.1的 ssm web项目(红色箭头指向注意删除web.

spring,springmvc,mybatis基本整合(一)--xml文件配置方式(2)

spring,springmvc,mybatis基本整合(一)–xml文件配置方式(2)之mapper接口 一,整合结构 二,所需jar包 如上图. 三,整合配置 1,web.xml文件 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://j

Spring、SpringMVC、Hibernate整合

1.整合Spring.SpringMVC 2.整合Spring.Hernate 3.配置web.xml文件 4.配置Tomcat,并且配置为热部署 5.在此不过多介绍Spring.SpringMVC整合 6.Spring与Hibernate整合关键代码如下 <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <pr

SSM框架Spring+SpringMVC+MyBatis——详细整合教程

摘要: 包括SQL Maps和Data Access ObjectsDAOMyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的... 摘要:   spring MVC属于SpringFrameWork的后续产品已经融合在Spring Web Flow里面.Spring MVC 分离了控制器.模型对... 1.基本概念 1.1.Spring Spring是一个开源框架Spring是于2003 年兴起的一个轻量级的Java 开发框架由Rod Johnson 在其著作Expert 

Spring+SpringMVC+MyBatis+easyUI整合基础篇(二)牛刀小试

承接上文,该篇即为项目整合的介绍了. 废话不多说,先把源码和项目地址放上来,重点要写在前面. github地址为ssm-demo 你也可以先体验一下实际效果,点击这里就行啦 账号:admin 密码:123456 从构思这个博客,一直到最终确定以这个项目为切入点,中间也是各种问题出现,毕竟是新人,所以也是十分的小心,修改代码以及搬上github其实花了不少时间,但也特别的认真,不知道是怎么回事,感觉这几天的过程比逼死产品经理还要精彩和享受.或许是博客路上的第一站吧,有压力也有新奇,希望自己能坚持下

Spring+SpringMVC+Mybatis+Mysql整合实例【转】

本文要实现Spring+SpringMVC+Mybatis+Mysql的一个整合,实现了SpringMVC控制访问的页面,将得到的页面参数传递给Spring中的Mybatis的bean类,然后查找Mysql数据的功能,并通过JSP显示出来.建议可以先看笔者另一文章Mybatis与Spring整合创建Web项目 .笔者觉得整合过程中问题比较多的还是Spring+Mybatis的整合,SpringMVC的整合还是比较简单. Spring        Spring 是一个开源框架, Spring 是

简单易学的SSM(Spring+SpringMVC+MyBatis)整合

SSM(Spring+SpringMVC+MyBatis)的整合: 具体执行过程:  1.用户在页面向后台发送一个请求 2.请求由DispatcherServlet 前端控制器拦截交给SpringMVC管理,SpringMVC讲这个请求传递给Controller层处理. 同时请求由Listener监听到交付给Spring,Spring建立IOC容器. 3.Controller层中会调用相应的Service层的方法处理业务逻辑.此时Service从上一步中建立好的IOC容器获取对象,然后获取 到M

学习笔记——Spring+SpringMVC+MyBatis框架整合

一.Maven创建项目 1. 在Eclipse中选择New -> Project -> Maven -> Maven Project 2. 选择默认workspace之后建立maven-webapp 3. 填写Group Id和Artifact Id(项目名称) 4. 建立工程后发现目录结构报错 5. 为了避免乱码,右键点击工程选择Properties -> Resource,选择编码方式为UTF-8 6. 在Properties中选择Java Build Path -> J