【Spring + SpringMVC + Mybatis】 SSM 整合

2021-01-27 07:13

阅读:493

标签:配置   username   getbean   实例   some   sql数据库   lease   style   异常   

环境搭建要求:

软件环境:

- Windows7 x64 +

- IDEA 2018 +

- MySQL 5.0 +

- Tomcat 8 +

- Maven 3.0 + 

【建议:越新越好】

 

知识点:

- MySQL数据库操作

- Spring

- JavaWeb

- Mybatis

- 前端基础

 

设计过程:

分析需求 - 设计数据库 - 业务 - 前端界面

 

创建演示库:

CREATE DATABASE IF NOT EXISTS `ssm`;

 

创建演示的用户表

USE `ssm`;

CREATE TABLE `user`(
`user_id` INT PRIMARY KEY AUTO_INCREMENT,
`user_name` VARCHAR(10),
`user_password` VARCHAR(20));

 

插入演示数据

INSERT INTO `user` VALUES
(1,USER01,111111),
(2,USER02,222222),
(3,USER03,333333);

 

打开IDEA创建SSM整合工程

技术图片

 

配置POM.xml依赖

【测试完之后放上来的,所有依赖都在这里了】

    dependencies>

        
        
        dependency>
            groupId>junitgroupId>
            artifactId>junitartifactId>
            version>4.13version>
            scope>testscope>
        dependency>

        
        
        dependency>
            groupId>mysqlgroupId>
            artifactId>mysql-connector-javaartifactId>
            version>8.0.20version>
        dependency>


        
        dependency>
            groupId>org.projectlombokgroupId>
            artifactId>lombokartifactId>
            version>1.18.12version>
            scope>providedscope>
        dependency>

        dependency>
            groupId>org.slf4jgroupId>
            artifactId>slf4j-log4j12artifactId>
            version>1.6.6version>
        dependency>

        
        dependency>
            groupId>log4jgroupId>
            artifactId>log4jartifactId>
            version>1.2.17version>
        dependency>


        

        
        dependency>
            groupId>com.mchangegroupId>
            artifactId>c3p0artifactId>
            version>0.9.5.5version>
        dependency>

        
        dependency>
            groupId>org.apache.commonsgroupId>
            artifactId>commons-dbcp2artifactId>
            version>2.7.0version>
        dependency>

        
        dependency>
            groupId>org.apache.commonsgroupId>
            artifactId>commons-pool2artifactId>
            version>2.8.0version>
        dependency>

        
        dependency>
            groupId>com.alibabagroupId>
            artifactId>druidartifactId>
            version>1.1.22version>
        dependency>

        dependency>
            groupId>com.zaxxergroupId>
            artifactId>HikariCPartifactId>
            version>3.4.2version>
        dependency>

        

        
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-webmvcartifactId>
            version>5.2.6.RELEASEversion>
        dependency>

        
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-jdbcartifactId>
            version>5.2.6.RELEASEversion>
        dependency>


        
        dependency>
            groupId>org.mybatisgroupId>
            artifactId>mybatisartifactId>
            version>3.5.4version>
        dependency>

        
        dependency>
            groupId>org.mybatisgroupId>
            artifactId>mybatis-springartifactId>
            version>2.0.4version>
        dependency>

        
        dependency>
            groupId>org.aspectjgroupId>
            artifactId>aspectjweaverartifactId>
            version>1.9.5version>
        dependency>

        

        
        dependency>
            groupId>javax.servlet.jspgroupId>
            artifactId>javax.servlet.jsp-apiartifactId>
            version>2.3.3version>
            scope>providedscope>
        dependency>

        
        dependency>
            groupId>javax.servletgroupId>
            artifactId>javax.servlet-apiartifactId>
            version>4.0.1version>
            scope>providedscope>
        dependency>

        
        dependency>
            groupId>javax.servlet.jsp.jstlgroupId>
            artifactId>jstlartifactId>
            version>1.2version>
        dependency>

        
        dependency>
            groupId>org.apache.taglibsgroupId>
            artifactId>taglibs-standard-specartifactId>
            version>1.2.5version>
        dependency>

        
        dependency>
            groupId>org.apache.taglibsgroupId>
            artifactId>taglibs-standard-implartifactId>
            version>1.2.5version>
        dependency>

    dependencies>

 

考虑资源导出过滤问题

【一般配置文件不放在包里面就不需要写】


    build>
        resources>
            resource>
                directory>src/main/resourcesdirectory>
                includes>
                    include>**/*.propertiesinclude>
                    include>**/*.xmlinclude>
                includes>
                filtering>falsefiltering>
            resource>

            resource>
                directory>src/main/javadirectory>
                includes>
                    include>**/*.propertiesinclude>
                    include>**/*.xmlinclude>
                includes>
                filtering>falsefiltering>
            resource>
        resources>
    build>

Mybatis层的配置

Mybatis-Config.xml

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>


configuration>

Application-Context.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:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"

       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"


       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd

       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
"
>
   
beans>

Jdbc.properties

jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql:///ssm?serverTimezone=Asia/Shanghai
jdbc.username = root
jdbc.password = 123456

# The url may some poor,you can use this params
# useSSL=true
# useUnicode=true
# characterEncoding=utf-8
# serverTimezone=GMT

# The MySQL8.0+ Must add serverTimezone param
# And driver is :  com.mysql.cj.jdbc.Driver

# In MySQL5.0+
# The driver is : com.mysql.jdbc.Driver

Mybatis类型别名处理

typeAliases>
    package name="cn.dai.pojo"/>
typeAliases>

用户表的BeanClass编写

package cn.dai.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author ArkD42
 * @file SSM Integration
 * @create 2020 - 05 - 07 - 22:43
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer user_id;
    private String user_name;
    private String user_password;
}

Dao接口【Mapper接口】

可以不写映射器,但是最好写一个测试用

public interface UserMapper {

    @Select("SELECT * FROM `user`;")
    List getAllUser();

    @Select("SELECT * FROM `user` WHERE `user_id` = #{USER_ID};")
    User getUserById(@Param("USER_ID") Integer id);

    @Insert("INSERT " +
            "INTO `user`(user_name,user_password) " +
            "VALUES(#{user_name},#{user_password});")
    int addUser(User user);
    
    @Update("UPDATE `user` " +
            "SET user_name = #{user_name},user_password = #{user_password} " +
            "WHERE user_id = #{user_id};")
    int updateUserById(User user);
    
    @Delete("DELETE FROM `user` WHERE user_id = #{user_id};")
    int deleteUserById(@Param("USER_ID") Integer id);
}

UserMapper.xml

放在resources.mappers下面

你也可以放接口的包里一起,就是要注意资源导出【要补上那个pom.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="cn.dai.mapper.UserMapper">

mapper>

注册映射器给Mybatis-Config.xml

mappers>
    mapper resource="mappers/UserMappers.xml"/>
mappers>

 

配置LOG4J日志记录

Mybatis-Config.xml设置日志输出

【自己注意下约束的顺序要求】

settings>
    setting name="logImpl" value="LOG4J"/>
settings>

Log4J.properties

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

# Settings About ConsoleOutput
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

# Settings About FileOutput
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./resources/log/logging.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

# LogOutput Level
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

配置文件的命名和存放位置

技术图片

 

因为是和SLF4J的API一起用的

所以还要再加一个 SLF4J + LOG4J 的依赖

dependency>
            groupId>org.slf4jgroupId>
            artifactId>slf4j-log4j12artifactId>
            version>1.6.6version>
        dependency>

 

在要输出记录的类中设置日志实例

private static Logger logger = Logger.getLogger(Sample.class);

数据源【连接池】配置移交给Spring配置


 

Spring层的配置

连接参数、连接池、SQL会话工厂的配置


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

    
    bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        property name="dataSourceProperties">
            props>
                prop key="url">${jdbc.url}prop>
                prop key="user">${jdbc.username}prop>
                prop key="password">${jdbc.password}prop>
            props>
        property>
    bean>

    
    bean name="dataSource" class="com.zaxxer.hikari.HikariDataSource">
        constructor-arg name="configuration" ref="hikariConfig" />
    bean>

    


    bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        property name="dataSource" ref="dataSource" />

        
    bean>

实现UserMapper继承DaoSupport

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
    public List getAllUser() {
        return getSqlSession().getMapper(UserMapper.class).getAllUser();
    }

    public User getUserById(Integer id) {
        return getSqlSession().getMapper(UserMapper.class).getUserById(id);
    }

    public int addUser(User user) {
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    public int updateUserById(User user) {
        return getSqlSession().getMapper(UserMapper.class).updateUserById(user);
    }

    public int deleteUserById(Integer id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUserById(id);
    }
}

到Spring容器中注册

    
    bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        
        property name="basePackage" value="cn.dai.mapper"/>
    bean>

 

业务层的编写:

用户业务接口:

package cn.dai.service;

import cn.dai.pojo.User;

import java.util.List;

/**
 * @author ArkD42
 * @file SSM Integration
 * @create 2020 - 05 - 08 - 0:06
 */
public interface UserService {

    List queryAll();

    User queryOneById(Integer id);

    int addUser(User user);

    int changeUser(User user);

    int removeUserById(Integer id);
}

实现类

package cn.dai.service;

import cn.dai.mapper.UserMapper;
import cn.dai.pojo.User;

import java.util.List;

/**
 * @author ArkD42
 * @file SSM Integration
 * @create 2020 - 05 - 08 - 0:09
 */
public class UserServiceImpl implements UserService{

    private UserMapper userMapper;

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public List queryAll() {
        return userMapper.getAllUser();
    }

    public User queryOneById(Integer id) {
        return userMapper.getUserById(id);
    }

    public int addUser(User user) {
        return userMapper.addUser(user);
    }

    public int changeUser(User user) {
        return userMapper.updateUserById(user);
    }

    public int removeUserById(Integer id) {
        return userMapper.deleteUserById(id);
    }
}

 

以xml方式注册


    context:component-scan base-package="cn.dai.service"/>

    
    

 

或者注解:

技术图片

 

事务的配置:

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

 


 

测试调试程序:

 

连接池测试【数据源配置问题】

在前面的Hikari连接池配置中,很有可能配置错!!!

这里使用原生硬编码写一遍链接测试,再把容器配置对照着修改

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author ArkD42
 * @file SSM Integration
 * @create 2020 - 05 - 08 - 0:28
 */
public class HikariTest {

    private static Logger logger = Logger.getLogger(HikariTest.class);

    @Test
    public void connectTest() throws SQLException {
        HikariConfig hikariConfig = new HikariConfig();
        
        hikariConfig.setJdbcUrl("jdbc:mysql:///ssm?serverTimezone=Asia/Shanghai");
        hikariConfig.setUsername("root");
        hikariConfig.setPassword("123456");
        
        HikariDataSource dataSource = new HikariDataSource(hikariConfig);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }
}

 

然后测试容器实例

容器实例&业务层的调用 是否正常

import cn.dai.pojo.User;
import cn.dai.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * @author ArkD42
 * @file SSM Integration
 * @create 2020 - 05 - 08 - 0:23
 */
public class ServiceTest {

    @Test
    public void serviceTest(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringContexts\\Bean-Context.xml");
        System.out.println(applicationContext);
    }

    @Test
    public void serviceTest2(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringContexts\\Bean-Context.xml");

        UserService userService = applicationContext.getBean("userServiceImpl", UserService.class);

        List users = userService.queryAll();

        for (User user: users) {
            System.out.println(user);
        }
    }
}

SpringMVC层的配置

 技术图片

 

添加Web框架

技术图片

 

 

配置【转发中心】&【乱码过滤器】

【web.xml】

注意:转发中心加载的应该是所有导入的总容器

 
    servlet>
        servlet-name>MVC DispatcherCenterservlet-name>
        servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        
        init-param>
            param-name>contextConfigLocationparam-name>
            param-value>classpath:SpringContexts/Mvc-Context.xmlparam-value>
        init-param>
        
        load-on-startup>1load-on-startup>
    servlet>
    
    servlet-mapping>
        servlet-name>MVC DispatcherCenterservlet-name>
        url-pattern>/url-pattern>
    servlet-mapping>
    
    
    
    filter>
        filter-name>EncodingFilterfilter-name>
        filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        
        init-param>
            param-name>encodingparam-name>
            param-value>utf-8param-value>
        init-param>
    filter>
    
    filter-mapping>
        filter-name>EncodingFilterfilter-name>
        url-pattern>/*url-pattern>
    filter-mapping>

 

配置转发中心初始化加载的Spring容器

【Mvc-Context.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:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"

       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"


       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd

       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
"
>

beans>

 

回到Bean容器导入Mvc容器

    import resource="classpath:SpringContexts/Dao-Context.xml"/>
    import resource="classpath:SpringContexts/Service-Context.xml"/>
    import resource="classpath:SpringContexts/Mvc-Context.xml"/>

 

配置MVC的相关

【Mvc-Context.xml】

    
    mvc:annotation-driven />
    
    
    mvc:default-servlet-handler/>
    
    
    context:component-scan base-package="cn.dai.controller" />
    
    
    bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        property 


评论


亲,登录后才可以留言!