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);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM