當(dāng)前位置:首頁 > IT技術(shù) > 編程語言 > 正文

Mybatis, Spring , SpringMVC框架SSM整合
2022-04-18 10:56:24

SSM整合

Maven依賴包

        <!--        測試工具-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <!--        Spring重要核心-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.16</version>
        </dependency>

        <!--        SpringAOP織入-->
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!--        spring中的Mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

        <!--        mysql驅(qū)動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>

        <!--        spring的jdbc(使用連接池技術(shù)可不用)-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.16</version>
        </dependency>

        <!-- 數(shù)據(jù)庫連接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!--        Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <!--Servlet - JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

Maven資源過濾文件

<build>
   <resources>
       <resource>
           <directory>src/main/java</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
       <resource>
           <directory>src/main/resources</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
   </resources>
</build>

pojo實體類

實體類User

package com.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", pwd='" + pwd + ''' +
                '}';
    }

 /* getter 和 setter  */
}

dao層

數(shù)據(jù)庫相關(guān)配置與Mybatis

數(shù)據(jù)庫配置文件

database.properties

# 注意! 使用了 c3p0 數(shù)據(jù)庫鏈接池的屬性要設(shè)置為 jdbc.屬性名,不加會報錯!
jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
mybati核心配置

mybatis-config.xml , 也可以進(jìn)行mybatis其他的設(shè)置,如起別名等

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
        <!-- 將包內(nèi)的映射器接口實現(xiàn)全部注冊為映射器,注意配置文件要與接口同名同包 -->
        <package name="com.dao"/>
    </mappers>
</configuration>
Spring中dao層配置文件

spring-dao.xml

<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
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置整合mybatis -->
    <!-- 關(guān)聯(lián)數(shù)據(jù)庫配置文件 -->
    <context:property-placeholder location="classpath:database.properties"/>

    <!-- 2.設(shè)置mybatis數(shù)據(jù)源 -->
    <!--數(shù)據(jù)庫連接池
        dbcp 半自動化操作 不能自動連接
        c3p0 自動化操作(自動的加載配置文件 并且設(shè)置到對象里面)     -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置連接池屬性 -->
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!--        c3p0連接池的私有屬性-->
        <!--        <property name="maxPoolSize" value="30"/>-->
        <!--        <property name="minPoolSize" value="10"/>-->
        <!--        關(guān)閉連接后不自動commit-->
        <!--        <property name="autoCommitOnClose" value="false"/>-->
        <!--        獲取連接超時時間-->
        <!--        <property name="checkoutTimeout" value="10000"/>-->
        <!--        當(dāng)獲取連接失敗重試次數(shù)-->
        <!--        <property name="acquireRetryAttempts" value="2"/>-->
    </bean>

    <!-- 3.配置SqlSessionFactory對象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數(shù)據(jù)庫連接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 關(guān)聯(lián)MyBaties核心配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 4.配置掃描Dao接口包,動態(tài)實現(xiàn)Dao接口注入到spring容器中 -->
    <!--解釋 :https://www.cnblogs.com/jpfss/p/7799806.html
Mybatis在與Spring集成的時候可以配置MapperFactoryBean來生成Mapper接口的代理.
MapperFactoryBean 創(chuàng)建的代理類實現(xiàn)了 UserMapper 接口,并且注入到應(yīng)用程序中。 因為代理創(chuàng)建在運行時環(huán)境中(Runtime,譯者注) ,那么指定的映射器必須是一個接口,而 不是一個具體的實現(xiàn)類。
沒有必要在Spring的XML配置文件中注冊所有的映射器。相反,你可以使用一個MapperScannerConfigurer, 它將會查找類路 徑 下 的 映射器并自動將它們創(chuàng)建成MapperFactoryBean。
<注意!!!>, 沒有必要去指定SqlSessionFactory 或 SqlSessionTemplate , 因為MapperScannerConfigurer 將會創(chuàng)建 MapperFactoryBean,之后自動裝配。但是,如果你使 用了一個以上的 DataSource ,那么自動裝配可能會失效 。這種 情況下,你可以使用 sqlSessionFactoryBeanName 或 sqlSessionTemplateBeanName 屬性來設(shè)置正確的 bean 名 稱來使用。這就是它如何來配置的,<注意!!!>bean的名稱是必須的,而不是 bean 的引用,因 此,value 屬性在這里替代通常的 ref:

即: 這個掃描類幫我們做了這些事: 掃描指定包下的接口,獲得Mapper對象,隨后業(yè)務(wù)層將會用到此Mapper來進(jìn)行操作
ApplicationContext context = new ClassPathXmlApplicationContext("appconfig.xml");
UserDao userDaoMapper = context.getBean("daoMapper", DaoMapper.class).getMapper(UserDao.class);
-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 給出需要掃描Dao接口包 -->
        <property name="basePackage" value="com.dao"/>
    </bean>
</beans>

dao接口 UserMapper

package com.dao;
import com.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;

public interface UserMapper {
    List getAllUser();

    int addUser(User user);

    int deleteUser(@Param("id") int id);

    int updateUser(User user);

    User getUser(@Param("id") int id);
}

接口映射器(sql配置)

如果是配置文件,最好和接口同包同名 , 也可以在接口上使用注解

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dao.UserMapper">
    <insert id="addUser" parameterType="com.pojo.User">
        insert into `user`
        values (#{id}, #{name}, #{pwd});
    </insert>
    
    <delete id="deleteUser" parameterType="int">
        delete from `user` where id=#{id}
    </delete>

    <update id="updateUser" parameterType="com.pojo.User">
        update `user`
        set id = #{id},name = #{name},pwd = #{pwd}
        where id = #{id}
    </update>

    <select id="getUser" resultType="int">
        select * from `user`
        where id = #{id};
    </select>

    <select id="getAllUser" resultType="com.pojo.User">
        SELECT * from `user`
    </select>
</mapper>

service層(業(yè)務(wù)層)

Service接口 ,非必需,根據(jù)項目情況而定

package com.service;

import com.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

interface UserService {
    List getAllUser();

    int addUser(User user);

    int deleteUser(@Param("id") int id);

    int updateUser(User user);

    User getUser(@Param("id") int id);
}

Service實現(xiàn)類

ServiceImp

package com.service;

import com.dao.UserMapper;
import com.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImp implements UserService {

    /*
    業(yè)務(wù)層調(diào)用dao層(Mapper對象)來執(zhí)行對應(yīng)的數(shù)據(jù)庫操作; 對應(yīng)接口的MapperBean由Spring的MapperScannerConfigurer生成
    由于UserMapper的映射器對象已經(jīng)在spring-dao.xml配置中用掃描器注冊了,所以可以使用自動裝配
    此外: // 官方不建議字段自動裝配,而是推薦setter注入更靈活
     */
    @Autowired
    @Qualifier("userMapper")
    private UserMapper userMapper;
    
    @Override
    public List getAllUser() {
        return userMapper.getAllUser();
    }
    @Override
    public int addUser(User user) {
        return userMapper.addUser(user);
    }
    @Override
    public int deleteUser(int id) {
        return userMapper.deleteUser(id);
    }
    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }
    @Override
    public User getUser(int id) {
        return userMapper.getUser(id);
    }
}

Spring中Service層配置文件

<?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">

    <!-- 掃描service相關(guān)的bean -->
    <context:component-scan base-package="com.service" />
    
<!--    
             UserServiceImpl注入到IOC容器中,用 注解@Service來注冊bean了就不在需要 
    <bean id="UserServiceImpl" class="com.service.UserServiceImp">

             這里引用的userMapper,在spring-dao.xml中注入了,使用到了Spring自帶的掃描器 MapperScannerConfigurer 
        <property name="userMapper" ref="userMapper"/>
    </bean>
-->
    
    <!-- 配置事務(wù)管理器,為啥要在這里配置事務(wù)管理呢,因為業(yè)務(wù)層嘛,可能會有一些會回滾的操作,所以業(yè)務(wù)層才需要事務(wù)管理 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入數(shù)據(jù)庫連接池,在spring-dao.xml里配置啦 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

controller層

控制器

UserController.java

package com.controller;

import com.pojo.User;
import com.service.UserServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    /* controller層調(diào)用業(yè)務(wù)層,
     業(yè)務(wù)層通過 @Service 注解在Spring中注入了
     這里自動裝配 業(yè)務(wù)層實現(xiàn)類(bean對象)
     控制層通過調(diào)用業(yè)務(wù)層實現(xiàn)類來進(jìn)行對應(yīng)的業(yè)務(wù)操作
     */
    @Autowired  // 官方不建議字段注入 自動裝配,而是推薦setter注入更靈活更安全
    @Qualifier("userServiceImp")
    private UserServiceImp mapperImp;

    //由于類也有url,所以請求的url為:user/getAllUser
    @RequestMapping(value = "/getAllUser",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String getAllUser(){

        String date ="";
        List<User> users = mapperImp.getAllUser();
        for (User user:users){
            date+=user+"<br>" ;
            System.out.println(user);
        }
//返回數(shù)據(jù)
        return date;
    }
}

Spring中的控制層配置文件

spring-controller.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:mvc="http://www.springframework.org/schema/mvc"
       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
   http://www.springframework.org/schema/mvc
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 4.掃描web相關(guān)的bean -->
    <context:component-scan base-package="com.controller" />

    <!-- 配置SpringMVC -->
    <!-- 1.開啟SpringMVC注解驅(qū)動 -->
    <mvc:annotation-driven />
    <!-- 2.靜態(tài)資源默認(rèn)servlet配置-->
    <mvc:default-servlet-handler/>

    <!-- 3.配置jsp 設(shè)置ViewResolver視圖解析器相關(guān)屬性 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Spring整合所有應(yīng)用上下文配置

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <import resource="spring-dao.xml"/>   <!--引入dao層配置-->
    <import resource="spring-service.xml"/>     <!--引入業(yè)務(wù)層配置-->
    <import resource="spring-controller.xml"/>    <!--引入控制層層配置-->
</beans>

web配置

配置整個web應(yīng)用程序的配置文件``web.xml`

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--一定要注意:我們這里加載的是總的配置文件,之前被這里坑了
            tomcat是根據(jù)總配置文件來啟動的-->
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--encodingFilter-->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--Session過期時間(根據(jù)需要設(shè)置)-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

至此,所有的配置都做完了,完結(jié)撒花 ??????

本文摘自 :https://www.cnblogs.com/

開通會員,享受整站包年服務(wù)立即開通 >