SSM 整合 Spring+Spring MVC+MyBatis

SSM 整合

文章目录

  • SSM 整合
    • 1、基础环境
      • 1.1、目录结构
      • 1.2、 `mybatis-config.xml` 框架
      • 1.3、 `applicationContext.xml` 框架
      • 1.4、 `jdbc.properties` 框架
    • 2、 `MyBatis` 配置
      • 2.1、数据库 `URL`
      • 2.2、配置别名
      • 2.3、 `Mapper` 配置
    • 3、 `Spring` 配置
      • 3.1、`spring-dao.xml `
      • 3.2、`spring-service.xml`
      • 3.3、`spring-mvc.xml`
      • 3.4、导入到主配置文件
      • 3.5、 `web.xml`
    • 4、代码测试
      • 4.1、 `pojo`
      • 4.2、`Dao` 层
      • 4.3、 `Service` 层
      • 4.4、 `Controller` 层

1、基础环境

新建空白 maven 工程,右键点击 项目-> Add Frameworks Support -> Java EE -> 选中 Web Application (版本需大于等于4.0) -> OK

1.1、目录结构

SSM 整合 Spring+Spring MVC+MyBatis_第1张图片

1.2、 mybatis-config.xml 框架



<configuration>
configuration>

1.3、 applicationContext.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://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
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
beans>

1.4、 jdbc.properties 框架

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=
jdbc.username=
jdbc.password=

2、 MyBatis 配置

2.1、数据库 URL

jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai

MySQL 版本大于等于8.0,则需要在连接后加入时区参数。

2.2、配置别名

在文件 mybatis-config.xml 中的 configuration 标签下添加。

<typeAliases>
    <package name="com.lxc.pojo"/>
typeAliases>

2.3、 Mapper 配置

在类 UserMapper.java 同级目录中新建文件 UserMapper.xml



<mapper namespace="com.lxc.dao.UserMapper">
    <select id="findAllUser" resultType="user">
        select * from user
    select>

    <select id="findUser" resultType="user">
        select * from user where `id` = #{id}
    select>
mapper>

3、 Spring 配置

每一层分别使用一个配置文件进行配置

3.1、spring-dao.xml

负责 Dao


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

    
    <context:property-placeholder location="classpath:jdbc.properties"/>

    
    <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}"/>

        
        <property name="maxPoolSize" value="30"/>
        
        <property name="minPoolSize" value="10"/>
        
        <property name="autoCommitOnClose" value="false"/>
        
        <property name="checkoutTimeout" value="10000"/>
        
        <property name="acquireRetryAttempts" value="2"/>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.lxc.dao"/>
    bean>

beans>

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

    
    <context:component-scan base-package="com.lxc.service"/>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>

beans>

3.3、spring-mvc.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://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
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    
    <context:component-scan base-package="com.lxc.controller"/>

    
    <mvc:default-servlet-handler/>

    
    <mvc:annotation-driven>
        
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    bean>
                property>
            bean>
        mvc:message-converters>
    mvc:annotation-driven>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    bean>

beans>

3.4、导入到主配置文件

<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>

3.5、 web.xml


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

    <servlet>
        <servlet-name>dispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:applicationContext.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <session-config>
        <session-timeout>15session-timeout>
    session-config>

web-app>

4、代码测试

4.1、 pojo

User.java

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
    private int id;
    private String username;
    private String password;
}

4.2、Dao

UserMapper.java

package com.lxc.dao;

public interface UserMapper {

    List<User> findAllUser();

    User findUser(int id);

}

UserMapper.xml



<mapper namespace="com.lxc.dao.UserMapper">
    <select id="findAllUser" resultType="user">
        select * from user
    select>

    <select id="findUser" resultType="user">
        select * from user where `id` = #{id}
    select>
mapper>

4.3、 Service

UserService.java

public interface UserService {

    List<User> findAllUser();

    User findUser(int id);

}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }

    public User findUser(int id) {
        return userMapper.findUser(id);
    }
}

4.4、 Controller

@RestController
@RequestMapping("/hello")
public class HelloController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findall")
    public String hello1() throws JsonProcessingException {
        List<User> allUser = userService.findAllUser();
        return new ObjectMapper().writeValueAsString(allUser);
    }

    @RequestMapping("/find/{id}")
    public String hello2(@PathVariable("id") int id) throws JsonProcessingException {
        User user = userService.findUser(id);
        return new ObjectMapper().writeValueAsString(user);
    }

}
  • 结果目录

SSM 整合 Spring+Spring MVC+MyBatis_第2张图片

你可能感兴趣的:(Spring,Mybatis)