首页 > 代码库 > spring,springMvc和hibernate整合

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;@Repositorypublic 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;@Servicepublic 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;@Controllerpublic 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);    }}

 

spring,springMvc和hibernate整合