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

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

【工具】mysql

IDEA、SqlYog、Mavenweb

【簡述】spring

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

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

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

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

【開始搭建】mybatis

1、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標籤)

 

2、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配置文件,因此要按照依賴關係分別導入這些文件

3、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!"; } }
相關文章
相關標籤/搜索