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

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

SSM整合

Maven依賴包

        <!--        測(cè)試工具-->
        <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ū)動(dòng)-->
        <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實(shí)體類

實(shí)體類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.屬性名,不加會(huì)報(bào)錯(cuò)!
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)的映射器接口實(shí)現(xiàn)全部注冊(cè)為映射器,注意配置文件要與接口同名同包 -->
        <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 半自動(dòng)化操作 不能自動(dòng)連接
        c3p0 自動(dòng)化操作(自動(dòng)的加載配置文件 并且設(shè)置到對(duì)象里面)     -->
    <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)閉連接后不自動(dòng)commit-->
        <!--        <property name="autoCommitOnClose" value="false"/>-->
        <!--        獲取連接超時(shí)時(shí)間-->
        <!--        <property name="checkoutTimeout" value="10000"/>-->
        <!--        當(dāng)獲取連接失敗重試次數(shù)-->
        <!--        <property name="acquireRetryAttempts" value="2"/>-->
    </bean>

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

即: 這個(gè)掃描類幫我們做了這些事: 掃描指定包下的接口,獲得Mapper對(duì)象,隨后業(yè)務(wù)層將會(huì)用到此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ù)項(xiàng)目情況而定

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實(shí)現(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對(duì)象)來執(zhí)行對(duì)應(yīng)的數(shù)據(jù)庫操作; 對(duì)應(yīng)接口的MapperBean由Spring的MapperScannerConfigurer生成
    由于UserMapper的映射器對(duì)象已經(jīng)在spring-dao.xml配置中用掃描器注冊(cè)了,所以可以使用自動(dòng)裝配
    此外: // 官方不建議字段自動(dòng)裝配,而是推薦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來注冊(cè)bean了就不在需要 
    <bean id="UserServiceImpl" class="com.service.UserServiceImp">

             這里引用的userMapper,在spring-dao.xml中注入了,使用到了Spring自帶的掃描器 MapperScannerConfigurer 
        <property name="userMapper" ref="userMapper"/>
    </bean>
-->
    
    <!-- 配置事務(wù)管理器,為啥要在這里配置事務(wù)管理呢,因?yàn)闃I(yè)務(wù)層嘛,可能會(huì)有一些會(huì)回滾的操作,所以業(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中注入了
     這里自動(dòng)裝配 業(yè)務(wù)層實(shí)現(xiàn)類(bean對(duì)象)
     控制層通過調(diào)用業(yè)務(wù)層實(shí)現(xiàn)類來進(jìn)行對(duì)應(yīng)的業(yè)務(wù)操作
     */
    @Autowired  // 官方不建議字段注入 自動(dòng)裝配,而是推薦setter注入更靈活更安全
    @Qualifier("userServiceImp")
    private UserServiceImp mapperImp;

    //由于類也有url,所以請(qǐng)求的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);
        }
//返回?cái)?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ū)動(dòng) -->
    <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配置

配置整個(gè)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ù)總配置文件來啟動(dòng)的-->
            <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過期時(shí)間(根據(jù)需要設(shè)置)-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

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

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

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