MyBatis整合Spring+SpringMVC搭建一個web項目(SSM框架)


本文講解如何搭建一個SSM架構的web站點

【工具】

IDEA、SqlYog、Maven

【簡述】

該項目由3個模塊組成:dao(數據訪問層)、service(業務處理層)、web(表現層)

dao層:負責與數據庫交互,包含entity(實體類)和dao(持久化方法類)包

service層:負責業務處理和事務管理,將表現層輸入輸出的數據進行處理后持久化保存、返回表現層所需要的各種數據

web層:網站項目,負責與用戶交互

【開始搭建】

一、dao層

依賴:mysql-connector-java、mybatis、mybatis-spring、spring-jdbc、spring-core、spring-context、spring-aop

說明:該層需要配置與數據庫交互,我們用的是mysql數據庫,所以依賴mysql連接庫、mybatis庫;我們要和spring整合,所以依賴mybatis-spring庫、spring-jdbc為;另外我們需要使用spring來管理實例,所以需要依賴spring套餐(core、context、aop)

spring配置文件:

spring-dao.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">-->
        <!--<property name="driverClassName" value="com.mysql.cj.jdbc.MysqlDataSource"></property>-->
        <!--<property name="url" value="jdbc:mysql://localhost:3306/mycode_statistics?characterEncoding=UTF-8&amp;serverTimezone=GMT"></property>-->
        <!--<property name="username" value="root"></property>-->
        <!--<property name="password" value="root"></property>-->
    <!--</bean>-->
    <!--上面和下面這兩種配置數據源的方式都可以,效果是一樣的-->
    <bean id="dataSource" class="com.mysql.cj.jdbc.MysqlDataSource">
        <property name="url" value="jdbc:mysql://localhost:3306/mycode_statistics?characterEncoding=UTF-8&amp;serverTimezone=GMT"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="typeAliasesPackage" value="cc.yzeng.entity"></property>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property>
        <property name="basePackage" value="cc.yzeng.dao"></property>
    </bean>
</beans>

該文件配置了3個對象:

1:dataSource,數據源對象,用於連接數據庫,使用 org.springframework.jdbc.datasource.DriverManagerDataSource 或 com.mysql.cj.jdbc.MysqlDataSource 都可以,效果一樣。

2:sqlSessionFactoryBean,數據庫連接對象,用於打開與數據庫的連接,獲得會話,這是mybatis-spring里封裝的對象 org.mybatis.spring.SqlSessionFactoryBean ,封裝自mybatis的SqlSessionFactory,專門用於ioc容器管理的sqlSessionFactory對象

   屬性dataSource,引用數據源對象

     屬性typeAliasesPackage,用於給配置文件里的type指定別名,通常寫實體類包名,這樣我們在寫映射文件的時候經常用到實體類,就可以不用寫包名了

3:MapperScannerConfigurer,映射文件自動配置,用於將接口與配置文件自動關聯並生成代理類,這樣就可以通過接口->配置文件 來訪問數據庫了,而不用寫接口實現類

  屬性sqlSessionFactoryBeanName,引用sqlSessionFactoryBean對象

     屬性basePackage,指接口所在的包名,且配置文件也要放在與包名相同的目錄下

xml映射文件:

示例,路徑:resources/cc.yzeng.dao/UserDao.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cc.yzeng.dao.UserDao">
    <insert id="addUser" parameterType="User">
        insert into user values(#{userId},#{username},#{password},#{addTime},#{status})
    </insert>
    <select id="findUserByUserName" resultType="User">
        select * from user where username = #{username}
    </select>
    <select id="findAll" resultType="User">
        select * from user
    </select>
    <update id="updateUser" parameterType="User">
        update user
        <set>
            <if test="username != null">
                username = #{username},
            </if>
            <if test="status != null">
                status = #{status},
            </if>
        </set>
        where userId = #{userId}
    </update>
</mapper>

 

 以上是一個xml映射文件的示例,一個實體類對應一個映射文件,映射文件的路徑與接口的包名一致(而不是實體類的包名)、文件名與接口類名一致id與方法名一致(insert、select、update標簽)

 

二、service層

依賴:spring-jdbc、spring-core、spring-context、spring-aop、spring-tx、spring-aspects、dao層

spring配置文件:

spring-service.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:tx="http://www.springframework.org/schema/tx" xmlns:apo="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <import resource="spring-dao.xml"></import>
    <context:component-scan base-package="cc.yzeng.service"></context:component-scan>

    <!--事務管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    
    <tx:advice transaction-manager="transactionManager" id="transactionInterceptor">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"></tx:method>
            <tx:method name="create*" propagation="REQUIRED"></tx:method>
            <tx:method name="update*" propagation="REQUIRED"></tx:method>
            <tx:method name="*" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

    <apo:config>
        <apo:pointcut id="aa" expression="execution(public * cc.yzeng.service.impl.*.*(..))"></apo:pointcut>
        <apo:advisor advice-ref="transactionInterceptor" pointcut-ref="aa"></apo:advisor>
    </apo:config>

    <apo:aspectj-autoproxy></apo:aspectj-autoproxy>
</beans>

 

該配置文件由:導入dao配置文件、自動掃描組件、事務管理三塊組成,由於不同層都有一個spring配置文件,所以要按照依賴關系分別導入這些文件

三、web層

 依賴:spring-webmvc

 說明:依賴spring-webmvc這個庫會自動引用其它spring框架需要的庫

web.xml配置文件:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <!--所有請求指向springMVC的入口-->
  <servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--配置spring配置文件所在路徑,默認為WEB-INF目錄-->
      <param-name>namespace</param-name>
      <param-value>spring.xml</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--content目錄不走springMVC處理-->
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/content</url-pattern>
  </servlet-mapping>
</web-app>

spring.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"
       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.xsd">

    <!--自動掃描bean-->
    <context:component-scan base-package="cc.yzeng.controller"></context:component-scan>
    <!--視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

配置自動掃描指向controller目錄,就可以使用注解方式配置路由了。

controller類(示例):

package cc.yzeng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {
    @RequestMapping("home")
    @ResponseBody
    public String Home(){
        return "hello,world!";
    }
}

 


免責聲明!

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



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