欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

将Spring、SpringMVC和MyBatis-Plus整合到一个项目中

最编程 2024-07-22 07:21:55
...

前言

        好长时间没有发表文章了!!!这几个星期太忙了,又是论文,又是考试的!!!搞得我连续一个星期都是晚上2点睡。结果作业是做完了,也断更了。现在终于清闲下来了!!!这次总结一点关于整合ssm的东西,这个老早就想写了,之前时间不太允许。不多说,


开搞

1.先在eclipse中创建一个空的maven项目

2.导入所需要的的maven依赖(我这个版本有点低,可以去找比较新的版本maven地址

)

/*springmvc*/
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.7.RELEASE</version>
</dependency>
/*整合第三方的orm实现*/
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>5.1.7.RELEASE</version>
</dependency>
/*mysql*/
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
</dependency>
/*druid*/
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>
/*使用servlet的域*/
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>

3.编写jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/new?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
jdbc.username=root
jdbc.password=123456
jdbc.filters=stat
 
jdbc.maxActive=20
jdbc.initialSize=1
jdbc.maxWait=60000
jdbc.minIdle=10
jdbc.maxIdle=15
   
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
   
jdbc.validationQuery=SELECT 'x'
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
 
jdbc.maxOpenPreparedStatements=20
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=1800
jdbc.logAbandoned=true

4.编写mybatis-plus.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>

5.编写applicationContext.xml(这玩意儿可以直接复制粘贴用)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc 
    http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
        http://mybatis.org/schema/mybatis-spring 
        http://mybatis.org/schema/mybatis-spring-1.2.xsd
        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/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util 
        http://www.springframework.org/schema/util/spring-util-4.3.xsd">
    <!-- 扫描业务逻辑组件 -->
    <context:component-scan
        base-package="org.vector">
        <!-- 不扫控制器 -->
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

        <!-- 将数据源交给spring管理  -->
        <context:property-placeholder
        location="classpath:jdbc.properties"/>
    <bean class="com.alibaba.druid.pool.DruidDataSource"
        id="dataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="filters" value="${jdbc.filters}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
        <property name="maxWait" value="${jdbc.maxWait}"/>
        <property name="minIdle" value="${jdbc.minIdle}"/>
        <property name="validationQuery"
            value="${jdbc.validationQuery}"/>
        <property name="testWhileIdle" value="${jdbc.testWhileIdle}"/>
        <property name="testOnBorrow" value="${jdbc.testOnBorrow}"/>
        <property name="testOnReturn" value="${jdbc.testOnReturn}"/>
        <property name="maxOpenPreparedStatements"
            value="${jdbc.maxOpenPreparedStatements}"/>
        <property name="removeAbandoned"
            value="${jdbc.removeAbandoned}"/>
        <property name="removeAbandonedTimeout"
            value="${jdbc.removeAbandonedTimeout}"/>
        <property name="logAbandoned" value="${jdbc.logAbandoned}"/>
    </bean>

    <!--事务(提交,回滚)管理 org.springframework.jdbc.datasource.DataSourceTransactionManager -->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        id="dataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 基于注解的事务管理 -->
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
    
    <!-- 对mybatis的整合 -->
    <!-- <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory"> 
        这是MyBatis提供的 -->
    <!-- com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean 
        mybatis-plus提供的 -->
    <bean id="sqlSessionFactory"
        class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!-- 指定数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 指定mybatis全局配置文件的位置 -->
        <property name="configLocation"
            value="classpath:mybatis-config.xml"></property>
        <property name="typeAliasesPackage"
            value="org.vector.domain"></property>
        <!-- 指定myabtis配置文件的位置 -->
        <!-- <property name="mapperLocations" value="classpath:mapper/*.xml"></property> -->

        <!--注册mybatisPlus的全局策略配置 -->
        <!-- <property name="globalConfiguration" ref="globalConfiguration"></property> -->
    </bean>

    <!-- 配置扫描器 自动将mybatis接口的实现加入到ioc容器中 -->
    <!--org.mybatis.spring.mapper.MapperScannerConfigurer -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描所有的dao接口的实现,加入到ioc容器中 -->
        <property name="basePackage" value="org.vector.mapper"></property>
        <property name="sqlSessionFactoryBeanName"
            value="sqlSessionFactory"/>
    </bean>
</beans>

6.编写springmvc-servlet.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:p="http://www.springframework.org/schema/p"
    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-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- SpringMVC的配置文件 -->

    <!-- 包含网站跳转逻辑的配置 -->
    <context:component-scan
        base-package="org.vector" use-default-filters="false">
        <!-- 指定要扫描的包 -->
        <!-- 只扫描控制器就是只扫描有@Controller注解的类 -->
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller"></context:include-filter>
    </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>

    <!-- 两个标准配置 -->
    <!-- 将MVC不能处理的资源交给Tomcat这样就能实现动态静态资源都能访问成功 -->
    <!-- 在springMVC-servlet.xml中配置<mvc:default-servlet-handler />后,会在Spring 
        MVC上下文中定义一个org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler,它会像一个检查员,对进入DispatcherServlet的URL进行筛查, 
        如果发现是静态资源的请求,就将该请求转由Web应用服务器默认的Servlet处理,如果不是静态资源的请求,才由DispatcherServlet继续处理。 
        一般Web应用服务器默认的Servlet名称是"default",因此DefaultServletHttpRequestHandler可以找到它。 
        如果你所有的Web应用服务器的默认Servlet名称不是"default",则需要通过default-servlet-name属性显示指定: <mvc:default-servlet-handler 
        default-servlet-name="所使用的Web服务器默认使用的Servlet名称"/> -->
    <mvc:default-servlet-handler/>
    <!-- 能支持更高级的功能,配置注解驱动 相当于配置了最新的处理器映射器和最新的处理器适配器 -->
    <mvc:annotation-driven/>
</beans>

7.web.xml配置(这玩意儿还在WEB-INF下)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <!-- 开启spring  -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--开启springmvc  -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.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>
    <!--编码格式  -->
    <filter>
        <filter-name>CharacterEncodingFilter</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>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--支持rest风格的请求  -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--支持put和delete请求  -->
    <filter>
        <filter-name>HttpPutFormContentFilter</filter-name>
        <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HttpPutFormContentFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--监控druid  -->
    <filter>
        <filter-name>DruidWebStatFilter</filter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
        <init-param>
            <param-name>exclusions</param-name>
            <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>DruidWebStatFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>
</web-app>
配置文件结构

8.编写实体类

package org.vector.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

@TableName(value = "admin")
public class Admin implements Serializable {

    @TableId(value = "a_id", type = IdType.AUTO)
    private Integer aId;
    @TableField(value = "a_name", exist = true)
    private String aName;
    @TableField(value = "a_password", exist = true)
    private Integer aPassword;
    @TableField(value = "a_s_id", exist = true)
    private Integer asId;
    
    @TableField(exist = false)
    private List<Student> sList = new ArrayList<Student>();

    public List<Student> getsList() {
        return sList;
    }

    public Admin() {
        super();
    }

    public Admin(Integer aId, String aName, Integer aPassword, Integer asId, List<Student> sList) {
        super();
        this.aId = aId;
        this.aName = aName;
        this.aPassword = aPassword;
        this.asId = asId;
        this.sList = sList;
    }

    public void setsList(List<Student> sList) {
        this.sList = sList;
    }

    public Integer getaId() {
        return aId;
    }

    public void setaId(Integer aId) {
        this.aId = aId;
    }

    public String getaName() {
        return aName;
    }

    public void setaName(String aName) {
        this.aName = aName;
    }

    public Integer getaPassword() {
        return aPassword;
    }

    public void setaPassword(Integer aPassword) {
        this.aPassword = aPassword;
    }

    public Integer getAsId() {
        return asId;
    }

    public void setAsId(Integer asId) {
        this.asId = asId;
    }

    @Override
    public String toString() {
        return "Admin [aId=" + aId + ", aName=" + aName + ", aPassword=" + aPassword + ", asId=" + asId + "]";
    }

}

实体类对应的表

CREATE TABLE `admin` (
  `a_id` int(10) NOT NULL AUTO_INCREMENT,
  `a_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `a_password` int(100) DEFAULT NULL,
  `a_s_id` int(10) DEFAULT NULL,
  PRIMARY KEY (`a_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

9.写dao层

import org.springframework.stereotype.Repository;
import org.vector.domain.Admin;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

@Repository
public interface AdminMapper extends BaseMapper<Admin> {

}

10.写service层的接口

import java.util.List;

import org.vector.domain.Admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public interface AdminService {

    Admin findOne(String name, Integer pass);//根据账号密码找到一个

    List<Admin> getAllUsers(QueryWrapper<Admin> wrapper);//通过构造条件找到所有符合条件的

}

11.写service层的接口实现类

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.vector.domain.Admin;
import org.vector.mapper.AdminMapper;
import org.vector.service.AdminService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public List<Admin> getAllUsers(QueryWrapper<Admin> wrapper) {
        return adminMapper.selectList(wrapper);
    }

    @Override
    public Admin findOne(String name, Integer pass) {
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("a_name", name).eq("a_password", pass);
        return adminMapper.selectOne(qw);
    }

}

12.写controller层

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.vector.domain.Admin;
import org.vector.service.AdminService;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/findOne/{name}/{pass}")
    public Admin findOne(@PathVariable("name") String name, @PathVariable("pass") Integer pass,
            HttpServletRequest rep) {
        try {
            Admin findOne = adminService.findOne(name, pass);
            if (findOne != null) {
                rep.getSession().setAttribute("user", findOne);
                return findOne;
            } else {
                Admin find = new Admin();
                find.setaId(-1);
                return find;
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return null;
    }

    @DeleteMapping("/deleteOne")
    public int deleteOne(HttpServletRequest rep) {
        try {
            rep.getSession().removeAttribute("user");
            return 1;
        } catch (Exception e) {
            e.getStackTrace();
        }
        return 0;
    }

}
数据库数据
查找结果

推荐阅读