spring+springMvc+mybatis整合

spring+springMvc+mybatis整合

  1. 搭建一个maven 项目
    我们使用idea 创建一个maven 项目 File-New-Project-Maven
    spring+springMvc+mybatis整合_第1张图片
    填写好项目名称和组id
    spring+springMvc+mybatis整合_第2张图片
    目录如下
    spring+springMvc+mybatis整合_第3张图片

  2. 添加pom.xml jar 包

 <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>11maven.compiler.source>
    <maven.compiler.target>11maven.compiler.target>
    <srping.version>4.0.2.RELEASEsrping.version>
    <mybatis.version>3.2.8mybatis.version>
    <slf4j.version>1.7.12slf4j.version>
    <log4j.version>1.2.17log4j.version>
  properties>
  
<dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>3.8.1version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.1.0version>
      <scope>providedscope>
    dependency>

    
    <dependency>
      <groupId>javaxgroupId>
      <artifactId>javaee-apiartifactId>
      <version>7.0version>
      <scope>providedscope>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-coreartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-oxmartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-expressionartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-ormartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${srping.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${srping.version}version>
    dependency>
    
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.2.2version>
    dependency>
    
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.35version>
    dependency>
    
    <dependency>
      <groupId>commons-dbcpgroupId>
      <artifactId>commons-dbcpartifactId>
      <version>1.4version>
    dependency>
    
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>
    
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>${log4j.version}version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${slf4j.version}version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>${slf4j.version}version>
    dependency>
    
    
    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>fastjsonartifactId>
      <version>1.2.6version>
    dependency>
    <dependency>
      <groupId>org.codehaus.jacksongroupId>
      <artifactId>jackson-mapper-aslartifactId>
      <version>1.9.13version>
    dependency>
    
    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.3.1version>
    dependency>
    <dependency>
      <groupId>commons-iogroupId>
      <artifactId>commons-ioartifactId>
      <version>2.4version>
    dependency>
    <dependency>
      <groupId>commons-codecgroupId>
      <artifactId>commons-codecartifactId>
      <version>1.10version>
    dependency>
  dependencies>
  1. 创建整合需要包
    创建java 目录下controller,service,dao,pojo 和resources下mapper 目录
    spring+springMvc+mybatis整合_第4张图片
  2. 在resources 资源目录创建数据库配置文件jdbc.properties 和mybatis 日志打印mybatis-config
    jdbc.properties
driver=com.mysql.jdbc.Driver
url= jdbc:mysql://127.0.0.1:3307/ljh?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username=root
password=123456

initialSize=0 
maxActive=20 
maxIdle=20
minIdle=1
maxWait=60000

mybatis-config


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        
        <setting name="logImpl" value="STDOUT_LOGGING" />
    settings>
configuration>
  1. spring 整合mybatis
    在resources 创建一个application-mybatis.xml 文件用来整合 mybatis

<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">
    
    <context:component-scan base-package="com.ljh.ssm" >
        
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>
    
    
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    bean>
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        
        <property name="initialSize" value="${initialSize}">property>
        
        <property name="maxActive" value="${maxActive}">property>
        
        <property name="maxIdle" value="${maxIdle}">property>
        
        <property name="minIdle" value="${minIdle}">property>
        
        <property name="maxWait" value="${maxWait}">property>
    bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="mapperLocations" value="classpath*:com/ljh/ssm/mapper/*.xml">property>
        
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ljh.ssm.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    bean>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>
beans>
  1. spring 整合springMvc
    在resources 创建一个 application-springMvc.xml 文件用来整合springMvc

<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">
    
    <context:component-scan base-package="com.ljh.ssm" >
        
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>
    
    
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    bean>
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        
        <property name="initialSize" value="${initialSize}">property>
        
        <property name="maxActive" value="${maxActive}">property>
        
        <property name="maxIdle" value="${maxIdle}">property>
        
        <property name="minIdle" value="${minIdle}">property>
        
        <property name="maxWait" value="${maxWait}">property>
    bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="mapperLocations" value="classpath*:com/ljh/ssm/mapper/*.xml">property>
        
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ljh.ssm.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    bean>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>
beans>
  1. web.xml 文件
    在web.xm 配置编码过滤器和加载spring 配置文件

<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" id="WebApp_ID" version="3.0">
  <display-name>Archetype Created Web Applicationdisplay-name>
  
  <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>

  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:application-mybatis.xmlparam-value>
  context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

  
  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:application-springMvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
web-app>
  1. 编写数据库文件
    我们创建一张用户表,我们对他进行增删改查
create table ljh.user
(
    id          int auto_increment
        primary key,
    USERNAME    varchar(100) not null,
    SEX         varchar(2)   not null,
    AGE         int          not null,
    TEACHER_ID  int          null,
    CREATE_TIME datetime     null,
    UPDATE_TIME datetime     null,
    DELETE_AT   int          null
);
  1. pojo 实体类实现
    在pojo 目录下创建一个user.java
package com.ljh.ssm.pojo;

import java.util.Date;
/**
 * @author shkstart
 * @create 2021-12-2117:43
 */
public class User {
    private int id;
    private String username;
    private String sex;
    private int age;
    private int teacherId;
    private Date createTime;
    private Date updateTime;
    private int deleteAt;

    public String getSex() {
        return sex;
    }

    public User setSex(String sex) {
        this.sex = sex;
        return this;
    }

    public int getAge() {
        return age;
    }

    public User setAge(int age) {
        this.age = age;
        return this;
    }

    public int getTeacherId() {
        return teacherId;
    }

    public User setTeacherId(int teacherId) {
        this.teacherId = teacherId;
        return this;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public User setCreateTime(Date createTime) {
        this.createTime = createTime;
        return this;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public User setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
        return this;
    }

    public int getDeleteAt() {
        return deleteAt;
    }

    public User setDeleteAt(int deleteAt) {
        this.deleteAt = deleteAt;
        return this;
    }

    public int getId() {
        return id;
    }

    public User setId(int id) {
        this.id = id;
        return this;
    }

    public String getUsername() {
        return username;
    }

    public User setUsername(String username) {
        this.username = username;
        return this;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", teacherId=" + teacherId +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                ", deleteAt=" + deleteAt +
                '}';
    }
}
  1. dao 层实现
    分别在dao 层创建用户接口文件 UserMapper 和resource mapper 目录存放userMapper.xml 接口实现xml 文件
    UserMapper
package com.ljh.ssm.dao;

import com.ljh.ssm.pojo.User;

/**
 * @author shkstart
 * @create 2021-12-2115:43
 */

public interface UserMapper {
    //查询用户信息
    public User getUserInfo(int id);
    //添加用户信息
    public int insertUserInfo(User user);
    //删除用户信息
    public void deleteUserInfoById(int id);
    //修改用户信息
    public void updateUserInfo(User user);
}

UserMapper.xml


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ljh.ssm.dao.UserMapper">
    <resultMap id="map" type="com.ljh.ssm.pojo.User">
        <id property="id" column="id"/>
        <result property="teacherId" column="teacher_id"/>
        <result property="createTime" column="create_time" javaType="java.util.Date"/>
        <result property="deleteAt" column="delete_at"/>
    resultMap>
    
    <select id="getUserInfo" parameterType="int" resultMap="map">
        select *from user where id = #{id}
    select>

    
    <insert id="insertUserInfo" parameterType="com.ljh.ssm.pojo.User">
        -- 返回主键
        <selectKey resultType="int" keyProperty="id" order="AFTER">
            select @@IDENTITY as id
        selectKey>
        INSERT INTO user (USERNAME, SEX, AGE, TEACHER_ID, CREATE_TIME, UPDATE_TIME, DELETE_AT) VALUES (#{username}, #{sex}, #{age}, null, #{createTime}, null, null)
    insert>

    
    <delete id="deleteUserInfoById" parameterType="int">
        DELETE FROM user WHERE id = #{id}
    delete>

    
    <update id="updateUserInfo" parameterType="com.ljh.ssm.pojo.User">
        UPDATE user
        <set>
            <if test="username!=null">
                username = #{username}
            if>
            <if test="sex!=null">
                sex = #{sex}
            if>
            <if test="age!=0">
                age = #{age}
            if>
            <if test="createTime!=null">
                create_time = #{createTime}
            if>
        set>
        <where>
            id = #{id}
        where>
    update>
mapper>
  1. service 层实现
    在service 中我们创建两个文件,UserService接口文件和接口实现类文件UserServiceImpl
    spring+springMvc+mybatis整合_第5张图片
    UserService 实现
package com.ljh.ssm.service;

import com.ljh.ssm.pojo.User;
import org.springframework.stereotype.Service;

/**
 * @author shkstart
 * @create 2021-12-229:30
 */

public interface UserService {
    //查询用户信息
    public User getUserInfo(int id);
    //插入用户信息
    public int insertUserInfo(User user);
    //删除用户信息
    public void deleteUserInfoById(int id);
    //跟新用户信息
    public void updateUserInfo(User user);
}

UserServiceImpl 实现

package com.ljh.ssm.service.impl;

import com.ljh.ssm.dao.UserMapper;
import com.ljh.ssm.pojo.User;
import com.ljh.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author shkstart
 * @create 2021-12-229:31
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User getUserInfo(int id) {
        return userMapper.getUserInfo(id);
    }
    @Override
    public int insertUserInfo(User user) {
        return userMapper.insertUserInfo(user);
    }
    @Override
    public void deleteUserInfoById(int id) {
        userMapper.deleteUserInfoById(id);
    }
    @Override
    public void updateUserInfo(User user) {
        userMapper.updateUserInfo(user);
    }
}
  1. controller 层实现
    controller 实现接口调用
package com.ljh.ssm.controller;

import com.ljh.ssm.pojo.User;
import com.ljh.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author shkstart
 * @create 2021-12-2115:47
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * get 请求用户信息
     */
    @RequestMapping(value = "/userInfo/{id}",method = RequestMethod.GET)
    public User getUserInfo(@PathVariable int id){
        User userInfo = userService.getUserInfo(id);
        return userInfo;
    }

    /**
     * post 请求添加用户信息
     * @param user
     * @return
     */
    @RequestMapping(value = "/userInfo",method = RequestMethod.POST)
    public int addUserInfo(User user){
        user.setCreateTime(new Date());
        int i = userService.insertUserInfo(user);
        //返回主键id
        return user.getId();
    }

    /**
     * delete 删除请求
     * @param id
     */
    @RequestMapping(value = "/userInfo/{id}",method = RequestMethod.DELETE)
    public void deleteUserInfoById(@PathVariable int id){
        userService.deleteUserInfoById(id);
    }

    /**
     * put 请求更新用户信息
     * @param user
     */
    @RequestMapping(value = "/userInfo",method = RequestMethod.PUT)
    public void updateUserInfo(User user){
        userService.updateUserInfo(user);
    }
}
  1. 配置maven tomcat 插件
    在 pom.xml 里面配置tomcat7 插件
 <build>
    <plugins>

      <!-- tomcat插件控制 -->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <!--端口控制-->
          <port>8854</port>
          <!--项目路径控制意味着http://localhost:8080/abc-->
          <path>/ljh</path>
          <!--编码-->
          <uriEncoding>UTF-8</uriEncoding>
        </configuration>
      </plugin>
      <!-- maven插件控制 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>11</source>
          <target>11</target>
          <encoding>utf-8</encoding>
        </configuration>
      </plugin>

    </plugins>
  </build>

在idea 中配置启动
spring+springMvc+mybatis整合_第6张图片
14. 使用postman通过restful 风格调用controller 接口
get 方式查询用户信息
在这里插入图片描述
post 方式添加用户信息
spring+springMvc+mybatis整合_第7张图片
put 方式修改用户信息
spring+springMvc+mybatis整合_第8张图片
delete 方式删除用户信息
spring+springMvc+mybatis整合_第9张图片

你可能感兴趣的:(spring,intellij-idea,maven,java)